ComboBoxItem selection fires the TabControl_SelectionChanged Event

c#, events, user-interface, wpf

Solution

Set e.Handled to True in SelectionChanged event of ComboBox.

  private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            e.Handled = true;
        }

ComboBox and TabControl are derived from Selector, and SelectionChanged event is a routed event, so the child ComboBox' SelectionChanged will be routed to parent control TabControl. This is the WPF routed event behaviour. Routed event bubble routing is accroding to the logical tree, if you put a ComboBox in a TabItem of a TabControl, when the ComboBox.SelectionChanged event raised, the event will be routed to the TabControl. But, if the ComboBox is not in the logical tree of TabControl, then the event will not be routed to the TabControl.

Update You can check the object which fired the event in TabControl SelectionChanged event:

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.OriginalSource == tb)
        {

        }
    }

Problem

I've a ComboBox inside a TabItem. The problem is that when I select any ComoboxItem, the TabControl_SelectionChanged Event is fired. and I have some Functions inside that event that I don't want it to be implemented once i change the ComboBox selected item. ``` <TabControl x:Name="tb" HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497" SelectionChanged="TabControl_SelectionChanged"> <TabItem x:Name="tbi1" Header="TabItem"> <Grid Background="#FFE5E5E5"> <Label x:Name="lbl" Content="Label" Margin="196,86,172,148"/> <ComboBox HorizontalAlignment="Left" Margin="51,162,0,0" VerticalAlignment="Top" Width="120"> <ComboBoxItem Content="ComboBoxItem"/> <ComboBoxItem Content="ComboBoxItem"/> <ComboBoxItem Content="ComboBoxItem"/> </ComboBox> </Grid> </TabItem> <TabItem x:Name="tbi2" Header="TabItem"> <Grid Background="#FFE5E5E5"/> </TabItem> </TabControl> ``` Edit: Also i face that problem with hovering any control within the Tab item as it hovers the tabitem too.

Original source