Reputation: 936
I'd like to know how I can handle a KeyDown Event with MVVM in my ViewModel.
I have a TextBox and when the user hits a key, which is not a number, the input shouldn't be allowed. I'd normally do it with Code behind like this (not full code, just an easy example):
private void textBox1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
{
// Determine whether the keystroke is a number from the top of the keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
e.Handled = true;
}
}
Now I want to put this somehow in my ViewModel with a Command. I'm new to MVVM and I'm only using Bindings right now (which works fine :) ), but I don't know how to use a Command at all...
My TextBox looks i.e. like this:
<TextBox Text="{Binding MyField, Mode=TwoWay}"/>
ViewModel:
private string _myfield;
public string MyField{
get { return _myfield; }
set {
_myfield= value;
RaisePropertyChanged( ()=>MyField)
}
}
But the setter will only be called, when I leave the TextBox + I don't have access to the entered Key.
Upvotes: 4
Views: 13270
Reputation: 790
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}" />
</TextBox.InputBindings>
</TextBox>
Upvotes: 6
Reputation: 101
I know my answer is late but if someone has a similar problem. You must just set your textbox like this:
<TextBox Text="{Binding MyField, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Upvotes: 10
Reputation: 4434
I do this by using the interaction triggers. (this example uses the MVVM_Light framework for the command binding)
here is an example:
<textBox Text="{Binding MyField}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyDown">
<cmd:EventToCommand Command="{Binding MyCommandName}" CommandParameter="YouCommandParameter"/>
</i:EventTrigger>
</i:Interaction.Triggers>
<TextBox/>
Create a ICommand object in your view model with the name MyCommandName and add these to the top of your xaml:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd="http://www.galasoft.ch/mvvmlight"
You don't have to use the mvvm-light command. This is just what I use and I like it because it allows me to use the CanExecute method of the ICommand interface
hope this helps
Upvotes: 3