In C# WPF, why is my TabControl's SelectionChanged event firing too often?

牧云@^-^@ 提交于 2019-11-27 03:47:36

The TabControl.SelectionChanged is the same event as a ComboBox.SelectionChanged

It originates from Selector.SelectionChanged.

So, if you do not mark your event as handled in your event handler, it will bubble up the tree, and eventually arrive at your TabControl, which is causing this "firing too often" issue.

Mark your event as handled in your SelectionChanged of your ComboBox/ListBox/ListView/any other Selector you use in your DataGrid like so:

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

And this inconvenience will go away ;).

     private void tabControlName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is TabControl) //if this event fired from TabControl then enter
            {
                if (tabItemName.IsSelected)
                {
                    //Do your job here
                }
            }
        }

If you have added a handler with AddHandler in a parent element, all selection changes will fire the SelectionChanged-event. In this case, you can give your TabControl a name and then check in the EventHandler if the name of the OriginalSource is the name of your TabControl.

Another good approch is adding a handler to the tabControl.Items.SelectionChanged:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
  ItemCollection view = tabControl.Items;
  view.CurrentChanged += new EventHandler(view_CurrentChanged);
}

void view_CurrentChanged(object sender, EventArgs e)
{
  throw new NotImplementedException();
}

Maybe is not the xamly way, but is less pain as it only fires when an item is changed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!