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

Meh*_*Meh 8 navigation wpf tabstop

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

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

我尝试设置IsTabStop为true和TabNavigationfalse,但它也不起作用.

<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>
Run Code Online (Sandbox Code Playgroud)

Ed *_*lez 15

在您的窗口(或您不希望使用选项卡的控件的某些祖先)上,吞下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;
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

<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>
Run Code Online (Sandbox Code Playgroud)

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

   private void Window_PreviewKeyDown(object sender, KeyEventArgs e)

    {
        if (e.Key == Key.Tab)
        {
            e.Handled = true;
        }
    }
Run Code Online (Sandbox Code Playgroud)


jpi*_*son 5

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

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

<ListView ItemContainerStyle="{StaticResource ItemCommon}"
          KeyboardNavigation.TabNavigation="Once" />
Run Code Online (Sandbox Code Playgroud)

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