WPF - TabControl - Prevent Selection Change

女生的网名这么多〃 提交于 2019-12-12 09:43:48

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/4851315/wpf-tabcontrol-prevent-selection-change

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