我正在将一个TextBox绑定到我的ViewModel的一个属性。当用户单击ApplicationBar按钮时,就会调用一个命令(我使用的是BindableApplicationBar,它可以在NuGet上找到)。问题是,当用户键入TextBox并立即单击应用程序按钮时,不会调用TextBox的设置器,这意味着ButtonCommand使用的是旧文本。
我已经看到了很多解决方案,但我不能在我的情况下使用它们。唯一的“解决方案”是去掉ApplicationBar,使用键盘后面的按钮(当用户点击TextBox时弹出)。我使用的是Windows Phone,所以这就是为什么有一个KeyBoard...)。因此,用户必须单击其他位置才能使用按钮-> lostfocus。
一些解决方案:
Binding with UpdateSourceTrigger==LostFocus do not fire for Menu or Toolbar interaction
我不能使用UpdateSourceTrigger=PropertyChanged,而且我正在使用MVVM,所以我也不是很想使用CodeBehind。如果没有CodeBehind没有其他方法可以做到这一点,那也没问题。
发布于 2013-06-14 00:42:29
我以前使用过的一种解决方案是每当文本框的内容发生变化时更新绑定,而不是在失去焦点时更新绑定。
一种简单的、可重用的方法是使用行为。
如下所示:
public class RebindOnTextChanged : Behavior<TextBox>
{
protected override void OnAttached()
{
base.OnAttached();
this.AssociatedObject.TextChanged += this.TextChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
this.AssociatedObject.TextChanged -= this.TextChanged;
}
private void TextChanged(object sender, TextChangedEventArgs e)
{
var bindingExpression = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
}
} 它的用法如下:
<TextBox Text="{Binding SomeProperty}">
<i:Interaction.Behaviors>
<behaviours:RebindOnTextChanged />
</i:Interaction.Behaviors>
</TextBox>发布于 2013-06-14 00:23:50
问题(或者框架中的bug?)这里发生的是AppBar不是一个真正的Silverlight控件,所以在窃取焦点方面它的处理方式是不同的。我不确定这是否适合你的设计,但在我的一个应用程序中,我使用了以下模式:
void appBarButton_Click(object sender, EventArgs e)
{
// removal of focus from the TextBox to the Page will force the bind.
this.Focus();
// wait till the next UI thread tick so that the binding gets updated
Dispatcher.BeginInvoke(() =>
{
// at this point the binding is updated
MessageBox.Show(RandomText);
});
}这有点恶心,但我使用了一个助手函数来包装一些不同的路径,这样他们就不需要知道额外的分派,或者哪个控件在点击按钮后会偷走焦点。
https://stackoverflow.com/questions/17082730
复制相似问题