c# - 以编程方式切换选项卡控件中的选项卡
问题描述
我想知道如何在选项卡控件中切换到不同的选项卡。
我有一个主窗口,它有一个与之关联的选项卡控件,它指向不同的页面。我想从在不同选项卡中触发的事件切换到选项卡。当我尝试使用 TabControl.SelectedIndex 时出现错误“需要对象引用才能访问非静态、方法或属性‘MainWindow.tabControl’
这是我从 MainWindow 声明 TabControl 并尝试从不同选项卡切换到它的代码。
<TabControl Name="tabControl" Margin="0,117,0,0" SelectionChanged="tabControl_SelectionChanged" Background="{x:Null}" BorderBrush="Black">
<TabItem x:Name="tabMO" Header="MO" IsTabStop="False">
<Viewbox x:Name="viewMO" Margin="0,0,0,0" Stretch="Fill" StretchDirection="Both">
<local:ManufacturingOrder x:Name="mo" Height="644" Width="1322"/>
</Viewbox>
</TabItem>
<TabItem x:Name="tabOptimize" Header="Optimize" IsTabStop="False">
<Viewbox x:Name="viewOptimize" Margin="0,0,0,0" Stretch="Fill" StretchDirection="Both">
<local:EngineeringOptimization x:Name="Optimize" Height="644" Width="1600"/>
</Viewbox>
</TabItem>
</TabControl>
private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var cellInfo = dataGrid.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
var r = new Regex("[M][0-9]{6}");
if (r.IsMatch(content.ToString()))
{
MainWindow.tabControl.SelectedIndex = 4;
}
}
我尝试将其切换为私有静态 void 并收到相同的错误。
我还尝试了以下代码,创建了 MainWindow 的一个实例,并且没有错误,但是当我运行代码时,选定的选项卡在屏幕上没有改变。但是,如果我使用 MessageBox 来查看选定索引,那么我会看到我更改的选项卡索引。
private void dataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
var cellInfo = dataGrid.SelectedCells[0];
var content = (cellInfo.Column.GetCellContent(cellInfo.Item) as TextBlock).Text;
var r = new Regex("[M][0-9]{6}");
if (r.IsMatch(content.ToString()))
{
MainWindow frm = new MainWindow();
frm.tabControl.SelectedIndex = 4;
}
}
解决方案
看起来您的主要问题是您无法从您的ManufacturingOrder
或EngineeringOptimization
UserControls 中轻松访问 MainWindow 及其所有子窗口。这是正常的。有几种方法可以解决这个问题。一个简单的,它违反了一些 MVVM 原则,(但无论如何你都在这样做,所以我认为你不会介意)是检索你的MainWindow
对象的实例:
//Loop through each open window in your current application.
foreach (var Window in App.Current.Windows)
{
//Check if it is the same type as your MainWindow
if (Window.GetType() == typeof(MainWindow))
{
MainWindow mWnd = (MainWindow)Window;
mWnd.tabControl.SelectedIndex = 4;
}
}
一旦您检索到 MainWindow 的运行实例,您就可以访问它的所有成员。这已经过尽可能好的测试,无需访问您的特定自定义用户控件和实例。但这是一个非常标准的问题和解决方案。
您在问题中的最后一段代码走在正确的轨道上,但是您正在创建 MainWindow 的“新”实例。您必须检索当前正在运行的实例,而不是新实例。
推荐阅读
- javascript - 我们如何在通过控制器附加到 html 页面的 html 中使用 angularjs 范围变量?
- flutter - 如何解决 Flutter 上未使用 import 的问题?
- jquery - 在 mouseleave 上隐藏元素(仅在快速移动时?)
- java - 当子字符串包含某些字符时更改整个字符串
- local-storage - 第一次在 SwiftUI 中未保存和更新 UserDefaults
- python - Youtube API v 3 中的布尔 OR(Python 代码)
- r - 如何确定层次聚类中的聚类数量
- python - 用下一个递增数字填充空值 | PySpark | Python
- javascript - GWT:将处理程序添加到本机 js 事件 onafterprint
- java - 唯一标识JAVA中终止的线程