【问题标题】:Mvvm TextBox KeyDown EventMvvm TextBox KeyDown 事件
【发布时间】:2013-04-15 21:15:59
【问题描述】:

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

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

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;
    }
}

现在我想用一个命令把它放在我的 ViewModel 中。我是 MVVM 的新手,我现在只使用 Bindings(效果很好:)),但我根本不知道如何使用命令......

我的文本框看起来像这样:

<TextBox Text="{Binding MyField, Mode=TwoWay}"/>

视图模型:

private string _myfield;
public string MyField{
  get { return _myfield; }
  set { 
    _myfield= value;
    RaisePropertyChanged( ()=>MyField)
  }
}

但只有当我离开 TextBox + 我无权访问输入的 Key 时,才会调用 setter。

【问题讨论】:

  • 谢谢。另一个问题:即我点击我的文本框,这也会引发 GotFocus 事件吗?我有一个标准值为 0.00 的十进制文本框。当我在 TextBox 中单击时,该值应为“”(如果值 0.00 在 TextBox 中)。我看到 UpdateSourceTrigger 会在我每次输入内容时提升我的设置器,并且我必须根据输入检查/设置值......无论如何,“KeyDown”正在工作,但是 GotFocus 呢? PS:上面的问题显示了当我单击一个键时如何引发一个事件,但我想处理所有的 KeyDown 事件而不是一个特殊的键。 (没有隐藏代码)

标签: events mvvm keydown


【解决方案1】:

我知道我的回答迟了,但如果有人有类似的问题。你必须像这样设置你的文本框:

<TextBox Text="{Binding MyField, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>

【讨论】:

【解决方案2】:

以下方法用于处理 TextBox 中的“Enter”键:

<TextBox Text="{Binding UploadNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding 
          Key="Enter" 
          Command="{Binding FindUploadCommand}" />
    </TextBox.InputBindings>
</TextBox>

【讨论】:

    【解决方案3】:

    我通过使用交互触发器来做到这一点。 (本示例使用 MVVM_Light 框架进行命令绑定)

    这是一个例子:

    <textBox Text="{Binding MyField}">
         <i:Interaction.Triggers>
             <i:EventTrigger EventName="KeyDown">
                 <cmd:EventToCommand Command="{Binding MyCommandName}" CommandParameter="YouCommandParameter"/>
             </i:EventTrigger>
          </i:Interaction.Triggers>
    <TextBox/>
    

    在视图模型中创建一个名为 MyCommandName 的 ICommand 对象,并将其添加到 xaml 的顶部:

     xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
     xmlns:cmd="http://www.galasoft.ch/mvvmlight"
    

    您不必使用 mvvm-light 命令。这正是我使用的,我喜欢它,因为它允许我使用 ICommand 接口的 CanExecute 方法

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-21
      • 2023-03-23
      • 2012-03-07
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      相关资源
      最近更新 更多