Search code examples
wpfkeyboard-shortcutslost-focus

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


I want when the user presses up/down to move within a listview even thought that listview is not in focus. But if the user is typing in a textbox and presses up down not to navigate anymore in the listview. On possible solution is to add a PreviewKeyDown event for every element and if the captured key is up/down then pass it further down the tree but this solution does not seem very practical since I have a lot of elements.

Example code:

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

Solution

  • You could handle the PreviewKeyDown event of the parent window only:

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

    Then you don't need to handle it for any other element.

    And no, there is no pure XAML solution for this.