我发现 KeyboardNavigation 无法正常工作,因为它与 Ctrl-Tab 和 TabControl 相关。我整理了一个简单的原型,KeyboardNavigation.ControlTabNavigation="None" 似乎对使用 Ctrl-Tab 切换选项卡没有预期的影响,一旦我左键单击一个选项卡并且键盘焦点位于 TabControl 内。
但是,将 InputBindings 与 Command 结合使用可能会覆盖不需要的 Ctrl-Tab 默认行为。从那里,我发现KeyboardNavigation.TabNavigation="Cycle" 以及 TabNavigation 的其他其他选项似乎表现合理。使用以下资源链接中描述的 FocusManager 和其他技术应该可以让人们获得所需的键盘导航,尽管使用了一些违反直觉的技术。
必须为具有不需要的默认行为的每个控件设置 InputBindings,尽管例如,更复杂的解决方案可能会遍历可视化树来为特定类型的所有控件设置 InputBindings。我发现让命令根本不做任何事情来充分中和键序列。在我的示例中,我显示了一个用于测试的对话框。
注意,下面的命令绑定要求您以 WPF 4.0 为目标;有关如何针对 WPF 3.5 或更早版本的资源,请参阅帖子末尾的资源
在 XAML 中:
<TabControl
x:Name="tabControl1"
IsSynchronizedWithCurrentItem="True"
SelectedItem="{Binding SelectedTabItem}"
ItemsSource="{Binding TabItemViewModels}"
KeyboardNavigation.ControlTabNavigation="None"
KeyboardNavigation.TabNavigation="Continue">
<TabControl.InputBindings>
<KeyBinding Modifiers="Control"
Key="Tab"
Command="{Binding ShowDialogCommand}" />
</TabControl.InputBindings>
</TabControl>
注意,在上面的 XAML 中,KeyboardNavigation.ControlTabNavigation="None" 是无效的,可以消除。
在支持 DataContext 中,通常是 ViewModel:
声明你的绑定属性:
public RelayCommand ShowDialogCommand
{
get;
private set;
}
初始化属性;例如,可以在 ViewModel 的构造函数中(注意,RelayCommand 来自 MVVM-Light 库。):
ShowDialogCommand = new RelayCommand(() =>
{
MessageBox.Show("Show dialog box command executed", "Show Dialog Box Command", MessageBoxButton.OK, MessageBoxImage.Information);
});
资源:
Helpful StackOverflow post on KeyBindings
More detail on KeyBinding to a Command; describes special CommandReference technique needed if targeting WPF framewrok 3.5 or earlier
Microsoft's Focus Overview