0
votes

I have a TabControl in a WPF project that contains seven TabItems.
In one TabItem (TabA) I have a ComboBox bound to a list of items. The selected Item is bound to a property in my code-behind. This works fine, and I can change the property perfectly.
In another TabItem (TabB), I can change that same property in another way. The ComboBox will therefore relect the new value.

The problem is that when the ComboBox in TabA changes it's SelectedItem due to the property changing from TabB - the OnSelectionChanged event somehow bubbles up to the TabControl, and raises the TabControlSelectionChanged event - even though nothing has happened with the tabs at all.

When I look at the arguments to the TabControlSelectionChanged event

var selectedTab = e.AddedItems[0] as TabItem;

selectedTab is null.

Why is this happening, and how do I prevent it occurring?

2

2 Answers

1
votes

Evil Str has answered the question, but after his lead, I found another method.
In the ComboBox SelectionChanged event, just prevent the event from bubbling further.

private void ComboBoxOnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    // whatever code you want in here to handle the change of item
    e.Handled = true;
}
0
votes

This is happening because the TabControl.SelectionChanged is the same event as a ComboBox.SelectionChanged.

I have already faced this problem once. To prevent this from occurring, I used this code:

private void myTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is TabControl) //if this event fired from TabControl
            {
                if (tabItemName.IsSelected)
                {
                    //Do what you need here.
                }
            }
        }

You can adapt this code for what you need. I hope this helps you.