以编程方式切换选项卡控件中的选项卡

问题描述 投票:0回答:1

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

我有一个主窗口,它有一个与之关联的标签控件,它指向不同的页面。我想切换到在不同选项卡中触发的事件的选项卡。当我尝试使用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# wpf tabs tabcontrol
1个回答
0
投票

看起来您的主要问题是您无法从ManufacturingOrderEngineeringOptimization 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的运行实例,就可以访问其所有成员。这已经过测试,无需访问您的特定自定义UserControl和实例。但这是一个非常标准的问题和解决方案。

您在问题的最后一段代码中处于正确的轨道上,但您正在创建MainWindow的“新”实例。您必须检索当前正在运行的实例,而不是新实例。

© www.soinside.com 2019 - 2024. All rights reserved.