【问题标题】:WPF - keyboard shortcuts to be captured by control even if not focusedWPF - 即使没有获得焦点,也可以通过控件捕获键盘快捷键
【发布时间】:2017-06-14 07:49:18
【问题描述】:

我希望当用户按下向上/向下键在列表视图中移动时,即使认为列表视图不在焦点上。但是,如果用户在文本框中输入并向上按下不再在列表视图中导航。 可能的解决方案是为每个元素添加一个 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>

【问题讨论】:

    标签: wpf keyboard-shortcuts lost-focus


    【解决方案1】:

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

    【讨论】:

    • 是的,这是我在谷歌搜索后采取的路线,感谢您确认这是一个好方法的答案
    猜你喜欢
    • 2017-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-01
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    • 2010-11-12
    相关资源
    最近更新 更多