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键.
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屋!