TextBox 和默认 Button 绑定更新太晚 [英] TextBox and default Button binding does update too late

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

问题描述

我有一个带有这两个控件的简单 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.

但是当我输入一些文本并按回车键单击"默认按钮时,它不起作用.由于点击回车时焦点不会离开 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}"/>

这篇关于TextBox 和默认 Button 绑定更新太晚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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