WPF - 控件要捕获的键盘快捷方式,即使未聚焦



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

示例代码:

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

您只能处理父窗口的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 解决方案。

最新更新