WPF:如何在不禁用箭头键导航的情况下禁用选项卡导航? [英] WPF: How to disable tab navigation without also disabling arrow key navigation?
问题描述
我已在窗口中的所有控件上将 IsTabStop
设置为 false,因此当我按下 Tab 键时,焦点不会移动(我需要 Tab 键来做其他事情).但是这样做会破坏箭头键导航 - 我单击 ListView
中的一个项目,然后按向上/向下键不会再更改所选项目.
I have set IsTabStop
to false on all controls in my window, so that when I press the Tab key, the focus doesn't move (I need the Tab key for something else). But doing this breaks arrow key navigation - I click on an item in a ListView
and then pressing up/down doesn't change the selected item anymore.
有没有办法禁用标签导航,但不触摸箭头键导航?它们似乎是相关的.
Is there a way to disable tab navigation, but without touching arrow key navigation? They seem to be related.
我尝试将 IsTabStop
设置为 true 并将 TabNavigation
设置为 false,但它也不起作用.
I tried setting IsTabStop
to true and TabNavigation
to false, but it doesn't work either.
<ListView ItemContainerStyle="{StaticResource ItemCommon}" IsTabStop="False">
<ListView.Resources>
<Style x:Key="ItemCommon">
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="KeyboardNavigation.TabNavigation" Value="None"/>
<Setter Property="KeyboardNavigation.DirectionalNavigation" Value="Cycle"/>
</Style>
</ListView.Resources>
</ListView>
推荐答案
在您的窗口(或您不想使用 tab 的控件的某些祖先)上吞下 tab 键.
On your window (or some ancestor of the controls you don't want tab to work on) swallow the tab key.
您可以通过附加到 PreviewKeyDown 事件并在键是选项卡时设置 e.Handled = true 来吞下它.
You can swallow it by attaching to the PreviewKeyDown event and set e.Handled = true when the key is a tab.
纯代码背后:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.PreviewKeyDown += MainWindowPreviewKeyDown;
}
static void MainWindowPreviewKeyDown(object sender, KeyEventArgs e)
{
if(e.Key == Key.Tab)
{
e.Handled = true;
}
}
}
您也可以这样设置键盘处理程序:
You can also set a Keyboard handler as such:
<Window x:Class="TabSwallowTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
Keyboard.PreviewKeyDown="Window_PreviewKeyDown" >
<StackPanel>
<TextBox Width="200" Margin="10"></TextBox>
<TextBox Width="200" Margin="10"></TextBox>
</StackPanel>
</Window>
但您需要相应的事件处理程序:
but you'll need a corresponding event handler:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Tab)
{
e.Handled = true;
}
}
这篇关于WPF:如何在不禁用箭头键导航的情况下禁用选项卡导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!