在 TextBox 中输入时执行 viewmodels 命令 [英] Executing viewmodels command on enter in TextBox

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

问题描述

当用户在文本框中按下回车键时,我想在我的视图模型中执行一个命令.该命令在绑定到按钮时有效.

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 中使用它.我尝试了输入绑定,但它不起作用.

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>

我也尝试将工作按钮设置为默认,但按下回车时它不会被执行.

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

感谢您的帮助.

推荐答案

我知道我迟到了,但我得到了这个为我工作.尝试使用 Key="Return" 而不是 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,否则在失去焦点之前属性不会更新,按回车也不会失去焦点...

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 中输入时执行 viewmodels 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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