[英]WPF data binding does not work
這是我從字符串(History.current_commad)到文本框(tbCommand)的數據綁定:
history = new History();
Binding bind = new Binding("Command");
bind.Source = history;
bind.Mode = BindingMode.TwoWay;
bind.Path = new PropertyPath("current_command");
bind.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
// myDatetext is a TextBlock object that is the binding target object
tbCommand.SetBinding(TextBox.TextProperty, bind);
history.current_command = "test";
history.current_command正在更改,但文本框未更新。 怎么了?
謝謝
您看不到TextBlock
反映的更改的原因是因為current_command
只是一個字段,所以Binding
不知道何時進行了綁定。
最簡單的解決方法是讓History
類實現INotifyPropertyChanged
,將current_command
轉換為屬性,然后在PropertyChanged
的設置器中引發PropertyChanged
事件:
public class History : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
private string _current_command;
public string current_command
{
get
{
return _current_command;
}
set
{
if (_current_command == null || !_current_command.Equals(value))
{
// Change the value and notify that the property has changed
_current_command = value;
NotifyPropertyChanged("current_command");
}
}
}
}
現在,當您為current_command
分配一個值時,該事件將觸發,並且Binding
也將知道更新其目標。
如果您發現自己想綁定到它們的屬性的類很多,則應考慮將事件和helper方法移到基類中,這樣就不必重復編寫相同的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.