[英]LostFocus before ApplicationBar Command
我將TextBox
綁定到ViewModel的屬性。 當用戶單擊ApplicationBar按鈕時,正在調用命令(我使用的是BindableApplicationBar,可以在NuGet上找到它)。 問題在於,當用戶鍵入TextBox
並立即單擊“應用程序按鈕”時,不會調用TextBox
的設置器,這意味着ButtonCommand使用的是舊文本。
我已經看到了很多解決方案,但是我無法在自己的情況下使用它們。 唯一的“解決方案”是擺脫ApplicationBar並使用一個位於Keyboard后面的按鈕(當用戶單擊TextBox時彈出該按鈕。我使用的是Windows Phone,所以這就是為什么有KeyBoard的原因。) ..)。 因此,用戶必須單擊其他位置才能使用按鈕-> lostfocus。
一些解決方案:
與UpdateSourceTrigger == LostFocus綁定不會觸發菜單或工具欄交互
我不能使用UpdateSourceTrigger = PropertyChanged,而且我正在使用MVVM,所以我也不想使用CodeBehind。 如果沒有CodeBehind沒有其他方法可以做到這一點,那就可以了。
這里發生的問題(或框架中的錯誤?)是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);
});
}
這有點麻煩,但是我使用了一個輔助函數來包裝許多不同的路徑,以使他們不必知道額外的調度,也不必知道哪個控件在按下按鈕后會搶走焦點。
我過去使用的一種解決方案是,只要文本框的內容發生更改,而不是失去焦點時,就更新綁定。
一個簡單,可重用的方法就是行為。
像這樣:
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.