用于WPF TextBox的命令,当我们按Enter键时将触发该命令

Ary*_*nsi 72 .net c# wpf icommand

ButtonWPF应用程序中的Commands 绑定到VIEWMODEL类中的s 非常容易.我想为a实现类似的绑定TextBox.

我有一个TextBox和我需要将其绑定到Command一个触发,当我击中EnterTextBox被聚焦.目前,我正在为KeyUp事件使用以下处理程序,但它看起来很丑......我不能把它放在我的VIEWMODEL课堂上.

private void TextBox_KeyUp(object sender, KeyEventArgs e)
{
    if (e.Key == System.Windows.Input.Key.Enter)
    {
        // your event handler here
        e.Handled = true;
        MessageBox.Show("Enter Key is pressed!");
    }
}
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?

sar*_*arh 225

我遇到了同样的问题并在这里找到了解决方案,这里是代码示例:

<TextBox>
  <TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=CmdSomething}" Key="Enter" />
  </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

  • 注意,您可能需要在TextBox绑定上设置`UpdateSourceTrigger = PropertyChanged`才能生效. (13认同)
  • 理查德丁沃尔讲述了可怕的事实.我们需要的是两件事:(1)Button.IsDefault ="True"(2)TextBox Text Binding添加"UpdateSourceTrigger = PropertyChanged".而已.甚至sarh的回答是不被使用. (3认同)

Err*_*Efe 20

雅利安,并非每个WPF对象都支持命令.因此,如果您不想这样做,您需要从您的代码后面调用您的视图模型(稍微耦合)或使用一些MVVM消息传递实现来解耦它.有关示例,请参阅MVVM Light Messaging工具包.或者简单的使用触发器如下:

<TextBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyUp">
            <i:InvokeDataCommand Command="{Binding MyCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

  • 看到这是我在[此处](http://www.codeproject.com/Tips/170895/InputBinding-for-WPF-and-Silverlight-with-MVVM)上发现的一个很好的示例 (3认同)
  • 谢谢。当前事件触发器是 &lt;i:InvokeCommandAction Command="{Binding QuickSearchTextKeyUp}"/&gt; (2认同)

Nig*_*mes 12

我喜欢萨尔的答案,但它不会在我的程序工作,除非我改EnterReturn:

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Return" Command="{}" />
   </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)


小智 7

<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding AddCommand}" Key="Return" />
    </TextBox.InputBindings>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

我从这里得到答案