2013-06-13 38 views
1

我将一个TextBox绑定到我的ViewModel的属性。 当用户点击一个ApplicationBar按钮时,一个命令被调用(我正在使用BindableApplicationBar,它可以在NuGet上找到)。问题是,当用户键入TextBox并立即点击应用程序按钮时,TextBox的设置程序未被调用,这意味着ButtonCommand正在使用旧文本。ApplicationBar命令之前的LostFocus

我见过很多解决方案,但我不能在我的情况下使用它们。唯一的解决方案是摆脱ApplicationBar,并使用键盘背后的按钮(当用户点击TextBox时弹出,我使用的是Windows Phone,所以这就是为什么有KeyBoard。 ..)。所以用户必须点击其他地方才能使用按钮 - > lostfocus。

一些解决方案:

WPF Databind Before Saving

Binding with UpdateSourceTrigger==LostFocus do not fire for Menu or Toolbar interaction

我不能使用UpdateSourceTrigger =的PropertyChanged和我使用MVVM,所以我也真的不希望使用代码隐藏。如果没有其他的方式没有CodeBehind,那就没关系。

回答

0

我过去使用的一种解决方案是在文本框内容发生更改时更新绑定,而不是在焦点丢失时更新绑定。

一个简单的,可重复使用的方式来做到这一点是一种行为。

事情是这样的:

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> 
0

这里发生的问题(或框架中的错误?)是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); 
     }); 
    } 

这是一种总值但我用一个辅助函数来包装多个不同路径的那他们不需要知道额外的派遣情况,或者是在按下按钮后哪个控制器会集中注意力。

相关问题