如何在目标属性发生变化时更新源绑定?

时间:2012-09-17 20:02:56

标签: c# wpf xaml data-binding

我有两个文本框txt1txt2以及一个字符串依赖属性sprop

public static readonly DependencyProperty spropProperty = DependencyProperty.Register("sprop", typeof (string), typeof (MainWindow), new UIPropertyMetadata(string.Empty));

public string sprop
{
    get { return (string) this.GetValue(spropProperty); }
    set { this.SetValue(spropProperty, value); }
}

现在,如果我以这种方式在XAML中为txt1设置数据绑定:

Text="{Binding sprop, ElementName=window, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}
每当文字框文字发生变化时,

txt1即时更新sprop

但是如果我用C txt2这样设置数据绑定:

DataContext = this;
txt2.SetBinding(TextBox.TextProperty, "sprop");

然后txt2仅在失去焦点时更新sprop

如果sprop的文字使用C#代码更改,我该如何更新txt2


我尝试过:

DataContext = this;
var myBinding = new Binding("sprop");
myBinding.Source = this;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
txt2.SetBinding(TextBlock.TextProperty, myBinding);

2 个答案:

答案 0 :(得分:2)

您还需要在txt2中设置UpdateSourceTrigger,以便在属性更改后更新,您也可以在代码中设置:

Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myBinding.Mode = TwoWay;
myBinding.UpdateSourceTrigger = PropertyChanged;
myText.SetBinding(TextBlock.TextProperty, myBinding);

答案 1 :(得分:1)

您是否将txt2设置为Mode = TwoWay?