tags:

views:

3411

answers:

5

Hi,

Is there an event that an be used to determine when a tabcontrol's selected tab changes in WPF?

I have tried using TabControl.SelectionChanged - but it is getting fired many times when a child's selection within a tab is changed.

Thanks! Jon

+2  A: 

You could still use that event. Just check that the sender argument is the control you actually care about and if so, run the event code.

Nidonocu
perfect - thought about that once I posted as well - thanks!
Jon Kragh
A: 

That is the correct event. Maybe it's not wired up correctly?

<TabControl SelectionChanged="TabControl_SelectionChanged">
    <TabItem Header="One"/>
    <TabItem Header="2"/>
    <TabItem Header="Three"/>
</TabControl>

in the codebehind....

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int i = 34;
}

if I set a breakpoint on the i = 34 line, it ONLY breaks when i change tabs, even when the tabs have child elements and one of them is selected.

Muad'Dib
+4  A: 

I tied this in the handler to make it work:

void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {
      //do work when tab is changed
    }
}
Jon Kragh
+2  A: 

The event generated is bubbling up until it is handled.

This xaml portion below triggers ui_Tab_Changed after ui_A_Changed when the item selected in the ListView changes, regardless of TabItem change in the TabControl.

<TabControl SelectionChanged="ui_Tab_Changed">
  <TabItem>
    <ListView SelectionChanged="ui_A_Changed" />
  </TabItem>
  <TabItem>
    <ListView SelectionChanged="ui_B_Changed" />
  </TabItem>
</TabControl>

We need to consume the event in ui_A_Changed (and ui_B_Changed, and so on):

private void ui_A_Changed(object sender, SelectionChangedEventArgs e) {
  // do what you need to do
  ...
  // then consume the event
  e.Handled = true;
}
rolling
A: 

If you set the x:Name property to each TabItem as:

<TabControl x:Name="MyTab" SelectionChanged="TabControl_SelectionChanged">
    <TabItem x:Name="MyTabItem1" Header="One"/>
    <TabItem x:Name="MyTabItem2" Header="2"/>
    <TabItem x:Name="MyTabItem3" Header="Three"/>
</TabControl>

Then you can access to each tabitem at the event:

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (MyTabItem1.IsSelected)
    // do your staff
    if (MyTabItem2.IsSelected)
    // do your staff
    if (MyTabItem3.IsSelected)
    // do your staff
}
unexpectedkas