I am developing a simple desktop MVVM application with Avalonia and the Community Toolkit (the most recent stable versions to the date - Avalonia 11.00.2 and Community Toolkit 8.2.1).
I want it to be keyboard-controlled, having no button controls on the form.
How do I bind a command (a viewmodel method attributed with the Community Toolkit RelayCommandAttribute
) to a key press, e.g. F3?
In fact I am interested in both cases: when the view is a Window (the IClassicDesktopStyleApplicationLifetime
case) and when it is a UserControl (the ISingleViewApplicationLifetime
case) but any single one of these would already be helpful.
I have found out that the way I was trying to do this was correct, I just misspelled my command name.
Adding the following to the MainWindow.axaml
does the job binding MyCommand
to the F3 button:
<Window.KeyBindings>
<KeyBinding Gesture="F3" Command="{Binding MyCommand}" />
</Window.KeyBindings>
This works even though the actual command is defined in a viewmodel of MainView
which is a control within the main window (as well as when it is defined in a viewmodel of the window itself i.e. in both cases I have mentioned in the question).