WPF - 键盘快捷键即使没有获得焦点也会被控件捕获

WPF - keyboard shortcuts to be captured by control even if not focused

我希望当用户按下 up/down 在列表视图中移动时甚至认为列表视图未处于焦点。但是,如果用户在文本框中键入内容并按下向上键,则不再在列表视图中导航。 一个可能的解决方案是为每个元素添加一个 PreviewKeyDown 事件,如果捕获的键是 up/down 然后将它进一步传递到树中,但这个解决方案似乎不太实用,因为我有很多元素。

示例代码:

<StackPanel>
    <ListView x:Name="capturesUpDownWhenTextBoxNotFocused" ItemsSource="{Binding list}" ItemTemplate="{StaticResource template}">
        <ListView.InputBindings>
            <KeyBinding Key="Up" Command="{Binding upCommand}"></KeyBinding>
            <KeyBinding Key="Down" Command="{Binding downCommand}"></KeyBinding>
        </ListView.InputBindings>
    </ListView>
    <TextBox Text="random text"></TextBox>
    <Button Content="button"></Button>
    <ListView x:Name="doesNotCaptureUpDownEvenIfFocused" ItemsSource="{Binding activeFile.activeFilters}" ItemTemplate="{StaticResource template}"></ListView>
</StackPanel>

您只能处理父 window 的 PreviewKeyDown 事件:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        PreviewKeyDown += (s, e) => 
        {
            var viewModel = DataContext as YourViewModel;
            if(viewModel != null)
            {
                if (e.Key == System.Windows.Input.Key.Up)
                {
                    viewModel.upCommand.Execute(null);
                    e.Handled = true;
                }
                else if(e.Key == System.Windows.Input.Key.Down)
                {
                    viewModel.downCommand.Execute(null);
                    e.Handled = true;
                }
            }

        };
}

那么其他元素就不需要处理了

不,对此没有纯粹的 XAML 解决方案。