文本框和默认按钮绑定的更新确实为时已晚 [英] TextBox and default Button binding does update too late

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

问题描述

我有一个简单的WPF对话框,其中包含以下两个控件:

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

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

现在,当我在TextBox中输入一些文本并使用鼠标单击按钮时,一切工作都与预期的一样:TextBox将设置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键以单击"默认按钮时,它将不起作用.由于点击时焦点不会离开TextBox,因此绑定不会刷新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中解决此问题?在经典的后台代码中,我可能只会在MyCommand处理程序中调用"MyButton.Focus()",但是在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.

那现在呢?

推荐答案

将UpdateSourceTrigger添加到您的TextBox中,并将其值设为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}"/>

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

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