[英]How to update source bind when target's property changes?
我有兩個文本框txt1
和txt2
以及一個字符串依賴項屬性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
僅在失去焦點txt2
更新sprop
。
使用C#代碼更改txt2
的文本后,如何更新sprop
?
我試過的
DataContext = this;
var myBinding = new Binding("sprop");
myBinding.Source = this;
myBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
txt2.SetBinding(TextBlock.TextProperty, myBinding);
您還需要在txt2中設置UpdateSourceTrigger,以便在屬性更改后立即進行更新,也可以在代碼中進行設置:
Binding myBinding = new Binding("MyDataProperty");
myBinding.Source = myDataObject;
myBinding.Mode = TwoWay;
myBinding.UpdateSourceTrigger = PropertyChanged;
myText.SetBinding(TextBlock.TextProperty, myBinding);
您是否將txt2設置為Mode = TwoWay?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.