Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mvvm TextBox KeyDown Event

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.

like image 404
Rudi Avatar asked Nov 01 '25 12:11

Rudi


2 Answers

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}"/>
like image 198
konradg89 Avatar answered Nov 03 '25 02:11

konradg89


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>
like image 40
SurfingSanta Avatar answered Nov 03 '25 02:11

SurfingSanta