Randy Minder
Randy Minder

Reputation: 48392

WPF - TabControl - Prevent Selection Change

It seems that the WPF TabControl doesn't support the ability to cancel a selection change, since there is no SelectionChanging() event, only a SelectionChanged event. Has anyone figured out a way to do this?

The only way I have found is to attach to the PreviewMouseLeftButtonDown() event on each TabItem and set e.Handled to true if I don't want that particular page selected. This seems to work but is clunky.

Upvotes: 4

Views: 7692

Answers (1)

Ben
Ben

Reputation: 63

I found a way do do this using a style for a TabItem and then binding the Focusable property to a boolean that controls the behavior. Getting a binding to the parent view model was a bit wonky but that could probably be improved.

This is nice because it avoids tricks with click events which may not get fired if the user uses the keyboard for example.

<TabControl.Resources>
    <Style TargetType="{x:Type TabItem}">
        <Setter Property="Focusable"  Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.IsUpToDate}" />
        <Setter Property="HeaderTemplate">
             <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding Group}" />
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</TabControl.Resources>

Upvotes: 1

Related Questions