views:

182

answers:

2

I have a tabbed GUI with each tab containing a Frame. In one of these Frames there is a DataGrid. When the user selects this tab, I need my datagrid sorted, so I'm using the TabControl SelectionChanged event to trigger the sort. However, this event triggers every time an item is selected from the DataGrid, even though the tabs themselves remain untouched.

I've tried number of different events: GotFocus for a TabItem RequestBringIntoView for a TabItem

but they all seem to suffer from this problem. What is causing this?

+2  A: 

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 ;).

Arcturus
He would then have to handle every selector on every one of his tab pages. It's much easier to just look and see if e.OriginalSource is a Tab Control.
Bryan Anderson
True, but it would be cleaner though, if he just marked his event as Handled when the selector is done with it. :)
Arcturus
Thanks so much for pointing out the problem. As for the solution, I ended up adding "if (e.OriginalSource is System.Windows.Controls.TabControl)" to my TabControl.SelectionChanged event so I wouldn't have to create an event handler for my Datagrid.
Anders
Glad I could help ;)
Arcturus
+1  A: 

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.

HCL