WPF MVVM:文本框和默认按钮绑定更新是否为时已晚 [英] WPF MVVM: TextBox and default Button binding does update too late

查看:95
本文介绍了WPF MVVM:文本框和默认按钮绑定更新是否为时已晚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的WPF对话框,这两个控件:

I've got a simple WPF dialog with these two controls:

<TextBox Text="{Binding MyText}"/>
<Button Command="{Binding MyCommand}" IsDefault="True"/>

现在,当我在文本框中输入一些文字,并用鼠标点击按钮,一切工作像预期:文本框将设置MYTEXT和MyCommand被称为

Now, when I enter some text in the TextBox and click the button using the mouse, everything works like expected: the TextBox will set MyText and MyCommand is called.

但是,当我输入一些文字,然后按Enter点击默认按钮,这是行不通的。自从按下回车键的焦点不离开文本框,绑定不会刷新MYTEXT。因此,当MyCommand被称为(工作),MYTEXT将包含旧数据。

But when I enter some text and hit enter to "click" the default button, it does not work. Since on hitting enter the focus does not leave the TextBox, the binding will not be refresh MyText. So when MyCommand is called (which works), MyText will contain old data.

我如何解决这个问题的MVVM?在经典的code-后面我可能只是会叫MyButton.Focus()中的MyCommand处理程序,但在MVVM的MyCommand处理程序一无所知的按钮。

How do I fix this in MVVM? In classic code-behind I probably just would call "MyButton.Focus()" in the MyCommand handler, but in MVVM the MyCommand handler does know nothing about the button.

那么,什么now`?

推荐答案

添加UpdateSourceTrigger与PropertyChanged的值的文本框。文本框的默认行为是更新源,当失去汇入作业焦点。

Add the UpdateSourceTrigger to your TextBox with the value PropertyChanged. The default behavior of the Textbox is to update the source, when it´s lost focus.

<TextBox Text="{Binding MyText, UpdateSourceTrigger=PropertyChanged}"/>

这篇关于WPF MVVM:文本框和默认按钮绑定更新是否为时已晚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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