首页 > 解决方案 > 以编程方式切换选项卡控件中的选项卡

问题描述

我想知道如何在选项卡控件中切换到不同的选项卡。

我有一个主窗口,它有一个与之关联的选项卡控件,它指向不同的页面。我想从在不同选项卡中触发的事件切换到选项卡。当我尝试使用 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;
    }
}

标签: c#wpftabstabcontrol

解决方案


看起来您的主要问题是您无法从您的ManufacturingOrderEngineeringOptimizationUserControls 中轻松访问 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 的“新”实例。您必须检索当前正在运行的实例,而不是新实例。


推荐阅读