Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyBinding without a command in WPF

I've a simple WPF app, and I'd like to add what is known in the Win32 world as keyboard accelerators. It looks like KeyBinding is the ticket, but it requires binding to a Command object. I'm not using command objects, nor do I want to. Is there another way to get an event triggered when a ctrl-x key sequence is hit?

like image 943
Charles Avatar asked Mar 22 '26 12:03

Charles


1 Answers

The only reason that I can think of why anyone would not want to use command objects is if they have them in their mind associated with the viewmodel, while they want their keybinding to work exclusively within the view.

And indeed, if you try to declare an ICommand in the view, it is surprisingly hard to manage to bind the KeyBinding to it.

This is how I solved this problem in my project:

<Window x:Class="MyNamespace.MyView"
    (...)
    xmlns:local="clr-namespace:MyNameSpace"
    (...)
    <Grid>
        <Grid.InputBindings>
            <KeyBinding Key="R" Command="{Binding ReportCommand, 
                RelativeSource={RelativeSource AncestorType=local:MyView}}" />
    (...)

ReportCommand is an ICommand in MyView, not in the ViewModel.

like image 181
Mike Nakis Avatar answered Mar 25 '26 13:03

Mike Nakis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!