C# - How to handle XAML Keyboard in MVVM?
c#, mvvm, wpf, xaml
Solution
Input handling is a View concern, not a ViewModel concern, why would you want to move that to the ViewModel?
instead, delegate the application / business logic to the ViewModel, while keeping the Keyboard Input handling in the View:
public partial class MainWindow : Window
{
private MyViewModel ViewModel;
public MainWindow()
{
ViewModel = new MyViewModel();
}
public void keyDownEventHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl)
ViewModel.PushToTalk = true;
}
public void keyUpEventHandler(object sender, KeyEventArgs e)
{
if (e.Key == Key.LeftCtrl)
ViewModel.PushToTalk = false;
}
}
Notice how I moved the `PushToTalk` property to the ViewModel, because that is really part of the application logic and not the UI, while keeping Keyboard events at the View level. This does not break MVVM because you're not mixing UI and application logic, you're just placing things where they really belong.
Problem
Untill now, I'm using the .xaml.cs to handle the inputs. Here is my xaml head code : ``` <Window x:Class="My_Windows_App.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:vm="clr-namespace:My_Windows_App.ViewModel" Title="MainWindow" Height="600" Width="900" Keyboard.KeyDown="keyDownEventHandler" Keyboard.KeyUp="keyUpEventHandler"> ``` And here is a part of the MainWindow.xaml.cs code : ``` public partial class MainWindow : Window { private bool pushToTalk; public void keyDownEventHandler(object sender, KeyEventArgs e) { if (e.Key == Key.LeftCtrl) pushToTalk = true; } public void keyUpEventHandler(object sender, KeyEventArgs e) { if (e.Key == Key.LeftCtrl) pushToTalk = false; } } ``` How can I implent the same thing in MVVM ? Because as far as I understand, we can not bind a method, only properties, right ?