Home > Back-end >  C# WPF Allow selecting the same tab in TabControl multiple times
C# WPF Allow selecting the same tab in TabControl multiple times

Time:01-19

I have a WPF application which uses TabControl. When I select a tab that shows a list of items and then select an item it will open a new page under the same tab. What I would like to achieve is that I can click the selected tab button and get back to the item list (like some sort of back button). I tried different tabcontrol options and neither of them detected another click. One way would be to apply an overlay over tab button which would allow another click to reset the tab page. I searched on StackOverflow but haven't found a topic that would cover that issue. Is there a better way to achieve this?

Thanks, Jan

CodePudding user response:

You could handle the MouseLeftButtonDown event for the TabControl to detect whether a selected tab was clicked:

private void TabControl_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    if (e.Source is TabItem tabItem && tabControl.SelectedItem == tabItem)
    {
        MessageBox.Show("You clicked a selected TabItem!");
    }
}

Sample XAML:

<TabControl x:Name="tabControl" PreviewMouseLeftButtonDown="TabControl_MouseLeftButtonDown">
    <TabItem Header="1">
    </TabItem>
    <TabItem Header="2">
    </TabItem>
</TabControl>
  • Related