81

Button将WPF 应用程序中Command的 s绑定到类中的 s 非常容易VIEWMODEL。我想为 a 实现类似的绑定TextBox

我有一个TextBox,我需要将它绑定到当我在聚焦时击中时Command会触发的 a。目前,我正在为该事件使用以下处理程序,但它看起来很难看......而且我不能把它放在我的课堂上。EnterTextBoxKeyUpVIEWMODEL

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!");
    }
}

有一个更好的方法吗?

4

5 回答 5

247

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

<TextBox>
  <TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=CmdSomething}" Key="Enter" />
  </TextBox.InputBindings>
</TextBox>
于 2012-05-05T21:53:47.587 回答
21

Aryan,并非每个 WPF 对象都支持命令。因此,如果您不想这样做,您将需要从您的代码中调用您的视图模型(有点耦合)或使用一些 MVVM 消息传递实现来解耦它。有关示例,请参阅MVVM 轻消息工具包。或者像这样简单的使用触发器:

<TextBox>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyUp">
            <i:InvokeDataCommand Command="{Binding MyCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>
于 2011-07-30T09:17:13.567 回答
18

我喜欢 Sarh 的回答,但它在我的程序中不起作用,除非我Enter改为Return

<TextBox>
    <TextBox.InputBindings>
        <KeyBinding Key="Return" Command="{}" />
   </TextBox.InputBindings>
</TextBox>
于 2014-08-29T23:16:29.200 回答
5
<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding AddCommand}" Key="Return" />
    </TextBox.InputBindings>
</TextBox>

我从这里得到答案

于 2020-07-24T09:09:44.880 回答
-9

您可以将 AcceptReturn 属性设置为 true。

 <TextBox AcceptsReturn="True" />
于 2015-01-02T12:42:48.063 回答