对TextBox使用数据绑定时,如果TextBox的Text属性值发生改变,只有在TextBox失去焦点时,Text的值才会被更新到数据源,这种方式有一些情况下并不适用,我需要Text值的改变能实时反映到数据源.
要修改更新模式,可以在绑定时设置
<TextBlock Text="{Binding UserName, UpdateSourceTrigger= Explicit}"/>
在windows phone 的silverlight中 UpdateSourceTrigger只有两个值,一个是:Default,另一个是Explicit.数据绑定时,默认情况下就是Default,指的是在TextBox失去焦点时,
Text值会更新到数据源,如果设置成Explicit,需要手工调用一下
BindingExpression.UpdateSource(),这个Text值会更新到数据源.
// Summary:
// Defines constants that indicate when a binding source is updated by its binding
// target in two-way binding.
public enum UpdateSourceTrigger
{
// Summary:
// The binding source is updated automatically when the binding target value
// changes.
Default = 0,
//
// Summary:
// The binding source is updated only when you call the System.Windows.Data.BindingExpression.UpdateSource()
// method.
Explicit = 3,
}
基本思路是利用TextBox的TextChanged事件去调用UpdateSource()
<TextBox Text="{Binding UserName, UpdateSourceTrigger= Explicit}"
TextChanged="TextBox_TextChanged_1"/>
private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
TextBox tb = sender as TextBox;
BindingExpression be = tb.GetBindingExpression(TextBox.TextProperty);
be.UpdateSource();
}
这个效果就实现了...
可以把这个段码用behaviour封装一下.这样复用性就强了.