在wpf上单击按钮时切换选项卡

时间:2016-01-12 19:56:00

标签: wpf tabs

我有4个标签,点击按钮移动到前面它应该更改下一个标签。但是在四个标签中,标签2是隐藏的,我不希望它显示。因此,如果屏幕位于选项卡1,则向前移动时应显示选项卡3,然后从选项卡3显示选项卡4.同样,如果它在选项卡3处向后移动,它应该转到选项卡1而不显示选项卡2.我尝试了这个实现,但它仍然转到标签2。

        private void movefront_click(object sender, RoutedEventArgs e)
    {
        if (tabIUWM.SelectedIndex == 2)
        {
            TabStudyAreaInterface.Visibility = Visibility.Visible; //tabstudyareainterface is the name of tab 2
        }
        else
        {
            tabIUWM.SelectedIndex = tabIUWM.SelectedIndex + 1;
        }        

    }
    private void moveback_click(object sender, RoutedEventArgs e)
    {

        if (tabIUWM.SelectedIndex == 2)
        {
            TabStudyAreaInterface.Visibility = Visibility.Visible;

        }
        else
        {

            tabIUWM.SelectedIndex = tabIUWM.SelectedIndex - 1;
        }

        if (tabIUWM.SelectedIndex == -1)
        {
            MessageBox.Show("This is the beginning screen");
        }

    }

谢谢:)

1 个答案:

答案 0 :(得分:1)

以下解决方案extension methods已添加到TabControl类,该类处理TabItem元素之间的来回导航。可以在单击事件中调用这些方法。 TabControl中隐藏/折叠的所有项目都将被忽略。

<强> MainWindow.cs

private void OnPrevClick( object sender, RoutedEventArgs e )
{
    TabControl.PrevVisibleTab();
}

private void OnNextClick( object sender, RoutedEventArgs e )
{
    TabControl.NextVisibleTab();
}

<强> TabControlExtensions.cs

internal static class TabControlExtensions
{
    public static void PrevVisibleTab( this TabControl tabControl )
    {
        var visibleTabs = tabControl.Items
            .OfType<TabItem>()
            .Where( t => t.Visibility == Visibility.Visible )
            .ToList();

        if( tabControl.SelectedItem == null )
        {
            tabControl.SelectedItem = visibleTabs.LastOrDefault();
            return;
        }

        if( !visibleTabs.Contains( tabControl.SelectedItem ) )
        {
            tabControl.SelectedItem = null;
            return;
        }

        int index = visibleTabs.IndexOf( tabControl.SelectedItem as TabItem ) - 1;
        if( index < 0 ) index += visibleTabs.Count;

        tabControl.SelectedItem = visibleTabs[index];
    }

    public static void NextVisibleTab( this TabControl tabControl )
    {
        var visibleTabs = tabControl.Items
            .OfType<TabItem>()
            .Where( t => t.Visibility == Visibility.Visible )
            .ToList();

        if( tabControl.SelectedItem == null )
        {
            tabControl.SelectedItem = visibleTabs.FirstOrDefault();
            return;
        }

        if( !visibleTabs.Contains( tabControl.SelectedItem ) )
        {
            tabControl.SelectedItem = null;
            return;
        }

        int index = ( visibleTabs.IndexOf( tabControl.SelectedItem as TabItem ) + 1 ) % visibleTabs.Count;

        tabControl.SelectedItem = visibleTabs[index];
    }
}