WPF How to intercept TabControl SelectionChanged event prior to it occurring?

518 views Asked by At

The approach i've taken is to detect if TabItem HEADER was clicked (and ignore clicks elsewhere).

Attempt 1:

If I hookup a mouse preview event in the TabControl's XAML's

<TabControl PreviewMouseLeftButtonDown = "TabControl_PreviewMouseLeftButtonDown">
<TabItem>
  <TabItem.Header>
    <StackPanel Orientation="Horizontal">
        <Image />
        <TextBlock />
        <TextBlock />
    </StackPanel>
  </TabItem.Header>
</TabItem>
   <TabItem Header="etc" />
   <TabItem Header="blah" />
   <TabItem Header="blah" />
</TabControl>

, the resulting event handler fires every time a click occurs in any element within the TabControl. This is to be expected, due to tunnelling / bubbling etc.

However, i want to detect if a click occurred in the TabHeader region, so i can take special action, and ignore all other cases.

Now in the event handler

private void TabControl_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
}

, none of the parameters sender, e.Source, e.OriginalSource is helpful to say with certainty that i clicked on the tabheader.

Attempt 2:

Moved the wiring of the event to individual TabItems instead of TabControl; Ditto, no joy, the parameters sender, source, etc are similarly useless.

Attempt 3:

Moved the wiring of the event to the StackPanel within the TabItem.

This looked more promising, in that the Preview Down event only occurs on a click to the header, which is just what i want; BUT sometimes the event does not fire, due to styling issues; The StackPanel may not necessarily cover the whole of the TabItem header region ! (And anyway, me thinks any solution dependent on styling would be dodge to the max)

What am i trying to achieve?

I want to intercept the TabControl's SelectionChanged event, prior to it occuring. i.e. in the WinForms world we would probably have some event called TabControl_SelectionChanging. But since in the advanced modern world of WPF /sarcasm there is no such luxury, i had to resort to PreviewMouseLeftButtonDown.

If this can be achieved via fine tuning either of the attempts above, or in some totally new way, please send ideas / code.

0

There are 0 answers