Search code examples
wpftabcontroltabitem

Find Active/Open Tab In WPF


So my situation is that I have a TabControl with two tabs inside a grid. A button is also in the grid, so it appears on both tabs. When this button is clicked, I would like it to be able to go Tab1 is open, do X and when Tab2 is open, do Y. I know I could just create a button in each tab and be fine, but I was wondering if there was a way to not do that.

Example:

  <Grid>
  <TabControl x:Name="sampTabControl">
            <TabItem x:Name="Tab1" Header="This Is Tab1"/>
            <TabItem x:Name="Tab2" Header="This Is Tab2"/>
  </TabControl>
  <Button Width="50" Height="50" Name="sampBtn" Click="doSomething_Click/>
  </Grid>


  private void doSomething_Click(object sender, System.Windows.RoutedEventArgs e)
    {
        if(Tab1.IsOpen //IsOpen is something I made up, does not actually work
           {
                 //Perform X Code
           }
        else if(Tab2.IsOpen) //IsOpen is something I made up, does not actually work
           {
                 //Perform Y Code
           }
    }

Solution

  • How about using the sampTabControl.SelectedIndex property?