在TextBox中的enter上执行viewmodels命令 [英] Executing viewmodels command on enter in TextBox

查看:72
本文介绍了在TextBox中的enter上执行viewmodels命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户在TextBox中按下Enter时,我想在视图模型中执行命令。
该命令在绑定到按钮时有效。

I want to execute a command in my viewmodel when the user presses enter in a TextBox. The command works when bound to a button.

<Button Content="Add" Command="{Binding Path=AddCommand}" />

但是我无法从TextBox中使用它。
我尝试了Inputbinding,但是没有用。

But I can't bring it to work from the TextBox. I tried an Inputbinding, but it didn't work.

<TextBox.InputBindings>
    <KeyBinding Command="{Binding Path=AddCommand}" Key="Enter"/>
</TextBox.InputBindings>

我也尝试将工作按钮设置为默认按钮,但在输入enter时不会执行

I also tried to set the working button as default, but it doesn't get executed when enter is pressed.

感谢您的帮助。

推荐答案

我知道我晚会晚了,但是我得到了这个工作。尝试使用 Key =返回 代替 Key = Enter

I know I am late to the party, but I got this to work for me. Try using Key="Return" instead of Key="Enter"

这里是完整示例

<TextBox Text="{Binding FieldThatIAmBindingToo, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding AddCommand}" Key="Return" />
    </TextBox.InputBindings>
</TextBox>

请确保在 UpdateSourceTrigger = PropertyChanged 中使用您的绑定,否则该属性将在焦点丢失之前不会更新,并且按Enter键也不会丢失焦点...

Make sure to use UpdateSourceTrigger=PropertyChanged in your binding, otherwise the property will not be updated until focus is lost, and pressing enter will not lose focus...

希望这会有所帮助!

这篇关于在TextBox中的enter上执行viewmodels命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆