Mvvm TextBox KeyDown事件

Rud*_*udi 1 events keydown mvvm

我想知道如何在ViewModel中使用MVVM处理KeyDown事件.

我有一个TextBox,当用户点击一个不是数字的键时,不应该允许输入.我通常会使用这样的代码(不是完整的代码,只是一个简单的例子):

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我想用命令以某种方式将它放在我的ViewModel中.我是MVVM的新手,我现在只使用Bindings(工作正常:)),但我根本不知道如何使用命令...

我的TextBox看起来像这样:

<TextBox Text="{Binding MyField, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)

视图模型:

private string _myfield;
public string MyField{
  get { return _myfield; }
  set { 
    _myfield= value;
    RaisePropertyChanged( ()=>MyField)
  }
}
Run Code Online (Sandbox Code Playgroud)

但是只有当我离开TextBox +我才能调用setter时,我无法访问输入的Key.

小智 6

我知道我的答案很晚,但如果有人有类似的问题.您必须像这样设置文本框:

<TextBox Text="{Binding MyField, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
Run Code Online (Sandbox Code Playgroud)


Sur*_*nta 6

以下内容用于处理文本框中的“Enter”键:

<TextBox Text="{Binding UploadNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding 
          Key="Enter" 
          Command="{Binding FindUploadCommand}" />
    </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)