9

我在窗口中的所有控件上都设置IsTabStop为 false,所以当我按下 Tab 键时,焦点不会移动(我需要 Tab 键来做其他事情)。但是这样做会破坏箭头键导航 - 我单击 a 中的一个项目ListView,然后按向上/向下键不会再更改所选项目。

有没有办法禁用标签导航,但不触摸箭头键导航?他们似乎是相关的。

我尝试设置IsTabStop为真和TabNavigation假,但它也不起作用。

<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>
4

2 回答 2

16

在您的窗口(或您不希望使用 tab 的控件的某些祖先)上吞下 tab 键。

您可以通过附加到 PreviewKeyDown 事件并在键是选项卡时设置 e.Handled = true 来吞下它。

纯代码背后:

 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;
            }
        }
    }

您还可以这样设置键盘处理程序:

<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>

但您需要一个相应的事件处理程序:

   private void Window_PreviewKeyDown(object sender, KeyEventArgs e)

    {
        if (e.Key == Key.Tab)
        {
            e.Handled = true;
        }
    }
于 2010-11-18T03:00:28.963 回答
5

我相信您想要的是在您的 ListView 上将KeyboardNavigation.TabNavigation附加属性设置为Once。我已经使用模板化的 ItemsControl 完成了此操作,它似乎给了我我期望的行为,例如 ListBox,其中进入控件的选项卡将选择第一项,但另一个选项卡将直接从列表框跳到下一个控制。

因此,按照这种方法,您的示例可能会缩短到此。

<ListView ItemContainerStyle="{StaticResource ItemCommon}"
          KeyboardNavigation.TabNavigation="Once" />

不过,我还没有使用 ListView 控件对此进行测试,但如果它对您有用,我不会感到惊讶。

于 2011-02-10T07:06:00.243 回答