Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - How to handle XAML Keyboard in MVVM?

Tags:

c#

mvvm

wpf

xaml

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 ?

like image 619
Elfayer Avatar asked Dec 06 '13 16:12

Elfayer


1 Answers

The following works for handling the "Enter" key in a TextBox:

<TextBox Text="{Binding UploadNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBox.InputBindings>
    <KeyBinding 
      Key="Enter" 
      Command="{Binding FindUploadCommand}" 
      CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />
</TextBox.InputBindings>

like image 144
SurfingSanta Avatar answered Oct 01 '22 06:10

SurfingSanta