Reputation: 582
I'm using MVVM pattern in my WPF project, now I'm facing a problem as title mentioned. I found some suggestions is to use KeyEventArgs.Handled = true;
like this:
private void PreviewKeyDown(object sender, KeyEventArgs e)
{
if ((e.Key.Equals(Key.Enter)) || (e.Key.Equals(Key.Return)))
{
e.Handled = true;
}
}
But I want to write it in ViewModel not code-behind of View. This example shows the way to handle Key Event with the MVVM pattern but I don't know how to pass KeyEventArgs
parameter for use.
Can anyone can help me? Is this the best way to do that?
Any recommendation or suggestion would be appreciated.
Thanks in advance.
Upvotes: 4
Views: 2077
Reputation: 3526
You can easily handle enter key press event, I have handled datagrid enter key press event like below code:
<DataGrid.InputBindings>
<KeyBinding Key="Enter" Command="{Binding Path=DataContext.HandleEnterKeyCommand,
RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}" />
</DataGrid.InputBindings>
Now, you can write your logic in viewmodel through command.
Upvotes: 2