![](/img/trans.png)
[英]C# WinForms, Adding tabs to a tab control, then adding a control to each tab programmatically
[英]Programmatically switching tabs in a Tab Control
我想知道如何在选项卡控件中切换到不同的选项卡。
我有一个主窗口,它有一个与之关联的选项卡控件,它指向不同的页面。 我想从不同选项卡内触发的事件切换到选项卡。 当我尝试使用 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;
}
}
我尝试将其切换为私有静态无效并收到相同的错误。
我还尝试了以下代码,创建了 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 的运行实例,您就可以访问其所有成员。 这已经过测试,无需访问您的特定自定义 UserControls 和实例。 但这是一个非常标准的问题和解决方案。
您在问题中的最后一段代码走在正确的轨道上,但是您正在创建 MainWindow 的“新”实例。 您必须检索当前正在运行的实例,而不是新实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.