WPF:如何在不禁用箭头键导航的情况下禁用选项卡导航?

时间:2010-11-18 00:47:35

标签: wpf navigation tabstop

我已经在我的窗口中的所有控件上将IsTabStop设置为false,因此当我按Tab键时,焦点不会移动(我需要使用Tab键进行其他操作)。但是执行此操作会中断箭头键导航 - 我单击ListView中的项目,然后按向上/向下键不会再更改所选项目。

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

我尝试将IsTabStop设置为true,将TabNavigation设置为false,但它也不起作用。

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

2 个答案:

答案 0 :(得分:15)

在您的窗口(或您不希望标签处理的控件的某些祖先)上,吞下Tab键。

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

Pure Code Behind:

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

答案 1 :(得分:5)

我相信你想要的是将 KeyboardNavigation.TabNavigation 附加属性设置为ListView上的一次。我用模板化的ItemsControl做了这个,它似乎给了我像ListBox那样的行为,其中控件中的选项卡将选择第一个项目,但是另一个选项卡将从列表框中直接选中并进入下一个控制。

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

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

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

相关问题