在Silverlight/WPF的BindingExpression中,我們可以對一個Bind定義UpdateSourceTrigger屬性,但是在Silverlight里只提供了顯式更新和默認方式(即失去焦點時觸發),
所以如果我們需要TextBox在輸入時即進行數據源的更新,我們需要進一步處理一下,那么如果你熟悉這個功能的話,你在網上能很快搜索出來類似下面的Code:
TextBox txt = sender as TextBox;
var bindingExpression = txt.GetBindingExpression(TextBox.TextProperty);
if (bindingExpression != null)
{
bindingExpression.UpdateSource();
}
那么本篇我仿照前一篇Grid擴展附加屬性的做法,實現這個功能,首先聲明UpdateExplictProperty
public static bool GetUpdateExplict(DependencyObject obj)
{
return (bool)obj.GetValue(UpdateExplictProperty);
}
public static void SetUpdateExplict(DependencyObject obj, bool value)
{
obj.SetValue(UpdateExplictProperty, value);
}
public static readonly DependencyProperty UpdateExplictProperty =
DependencyProperty.RegisterAttached("UpdateExplict", typeof(bool), typeof(TextBoxExtension), new PropertyMetadata(false, UpdateOnPropertyChangedPropertyCallback));
在UpdateOnPropertyChangedPropertyCallback中對TextBox的TextChanged進行處理,這里的處理邏輯與開頭的代碼是一致的.
最終我們在使用這個附加屬性時,如下的XAML就可以:
<TextBox Text="{Binding FirstName,Mode=TwoWay}" UpdateTextBox:TextBoxExtension.UpdateExplict="True"></TextBox>
其實對於這個功能,也可以使用Behavior去封裝,近期發的兩篇文章都是用附加屬性來解決問題的,實際也在強調附加屬性在Silverlight項目應用的意義所在。
下載代碼:TextBoxExtension.rar