按下回车键时数据未绑定
我正在使用 Silverlight 和MVVM 模式。
<TextBox Name="UserNameText" Text="{Binding Path=Username, Mode=TwoWay}" HorizontalContentAlignment="Stretch"/>
在此,我将 TextBox 绑定到属性 Username,当按下 Enter 键时,我正在视图模型中执行 LoginCommand。
private void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this._viewModel.LoginCommand.Execute(null);
}
}
当在文本框中输入用户名并从用户名文本框中按 ENTER 键时,将调用 LoginCommand,但用户名属性中的值不会更新。它仍然包含 null。
只要失去焦点,这些值就会受到限制。如何解决这个问题?
I am using Silverlight & MVVM pattern.
<TextBox Name="UserNameText" Text="{Binding Path=Username, Mode=TwoWay}" HorizontalContentAlignment="Stretch"/>
In this I had bound TextBox to a property Username and when Enter key is pressed and I am executing the LoginCommand in View Model.
private void LayoutRoot_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
this._viewModel.LoginCommand.Execute(null);
}
}
When username is entered in TextBox and ENTER key is pressed from the UserName TextBox, the LoginCommand is called, but the value is not updated in propery Username. It still contains null.
The values are bound if only there is a focus lost. How to fix this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改绑定中的
UpdateSourceTrigger=PropertyChanged
。默认情况下,TextBox 仅更新其在LostFocus
上的绑定值。将其设置为PropertyChanged
将使其在属性更改时更新绑定值。Change
UpdateSourceTrigger=PropertyChanged
in the Binding. By default, the TextBox only updates it's bound value onLostFocus
. Setting it toPropertyChanged
will make it so it updates the bound value anytime the property changes.你无法解决这个问题,这就是绑定的工作原理(它会在焦点丢失时更新,你是对的)。
但是,解决方案非常简单:您只需将文本框的文本作为命令的参数发送即可:
You cannot fix that, it is how binding works (It updates on focus lost, you are right).
However, the solution is pretty simple: you can just to send textbox's text as the command's parameter: