文中代码虽然是针对win8做的,但是windows phone中原理是一样的,希望对大家有帮助
如果绑定设为TwoWay的话,Binding target属性的变化会影响绑定源相应的属性。
但是问题是绑定源什么时候更新,在wpf中实际上有三种情况,取决于UpdateSourceTrigger的设置:
1. Default:根据控件不同其行为有所不同。比如TextBox,它失去焦点时候(LostFocus event)绑定源更新
2. PropertyChanged:意味着只要target变化,绑定源立即随之更新。比如,你在TextBox中输入的时候,绑定源的值是实时更新的。
3. Explicit:如果UpdateSourceTrigger设置为Explicti,那么绑定源不随target更新,除非你在后台调用UpdateSource方法。
但是,在Windows 8中不支持UpdateSourceTrigger设置,所以想要TextBox的绑定源随着TextBox输入实时更新就有点小麻烦了。
这里,我们给大家一个方法,基本原理就是处理TextBox的TextChanged event,
当用户输入的时候TextChanged event会被不断触发,
我们这里要做的就是通过这个event,模拟对绑定源的更新!
这里我们做一个TextBox的扩展类TextBoxEx,
在这个扩展类中封装了一个attached property,如果TextBox使用了它,我们就能获得TextBox的实例,然后通过一个Observable监听它的TextChanged event,然后将其Text属性赋值给我们的TextBoxEx的RealTimeText属性。
另外,我们注册RealTimeText属性为dependency property,这样当属性变化时候,可以触发我们设置的事件。
TextBoxEx的代码如下:
依赖属性使用非常简单,感觉就像TextBox原生的一样。Code:using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace DevDivTextChanged { public static class TextBoxEx { public static string GetRealTimeText(TextBox obj) { return (string)obj.GetValue(RealTimeTextProperty); } public static void SetRealTimeText(TextBox obj, string value) { obj.SetValue(RealTimeTextProperty, value); } public static readonly DependencyProperty RealTimeTextProperty = DependencyProperty.RegisterAttached("RealTimeText", typeof(string), typeof(TextBoxEx), new PropertyMetadata("HelloDevDiv", OnRealTimeTextChanged)); private static void OnRealTimeTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { string value = (string)e.NewValue; } public static bool GetIsAutoUpdate(TextBox obj) { return (bool)obj.GetValue(IsAutoUpdateProperty); } public static void SetIsAutoUpdate(TextBox obj, bool value) { obj.SetValue(IsAutoUpdateProperty, value); } public static readonly DependencyProperty IsAutoUpdateProperty = DependencyProperty.RegisterAttached("IsAutoUpdate", typeof(bool), typeof(TextBoxEx), new PropertyMetadata(false, OnIsAutoUpdateChanged)); private static void OnIsAutoUpdateChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var value = (bool)e.NewValue; var textbox = (TextBox)sender; if (value) { Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>( o => textbox.TextChanged += o, o => textbox.TextChanged -= o) .Do(_ => textbox.SetValue(TextBoxEx.RealTimeTextProperty, textbox.Text)) .Subscribe(); } } } }
Regards
Vincent
http://weib.com/xueyw

Reply With Quote

