我需要定義新的UI元素以及代碼中的數據綁定,因爲它們將在運行時實現。這是我正在嘗試做的簡化版本。在代碼中定義的WPF數據綁定問題不更新UI元素
數據模型:
public class AddressBook : INotifyPropertyChanged
{
private int _houseNumber;
public int HouseNumber
{
get { return _houseNumber; }
set { _houseNumber = value; NotifyPropertyChanged("HouseNumber"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(string sProp)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(sProp));
}
}
}
在代碼綁定:
AddressBook book = new AddressBook();
book.HouseNumber = 123;
TextBlock tb = new TextBlock();
Binding bind = new Binding("HouseNumber");
bind.Source = book;
bind.Mode = BindingMode.OneWay;
tb.SetBinding(TextBlock.TextProperty, bind); // Text block displays "123"
myGrid.Children.Add(tb);
book.HouseNumber = 456; // Text block displays "123" but PropertyChanged event fires
當數據被第一次綁定,文本塊與正確的門牌號碼進行更新。然後,如果我稍後在代碼中更改門牌號,則會觸發本書的PropertyChanged事件,但文本塊不會更新。誰能告訴我爲什麼?
感謝, 本
您是否嘗試設置斷點以查看它們在設置屬性時是否被擊中? – John 2009-01-02 11:24:48
是的,當本書的PropertyChanged事件觸發時,我會彈出一個消息框,這會在每次數據更新時發生。 – 2009-01-02 11:32:55
[最有趣的答案](http:// stackoverflow。com/a/406595/200449),國際海事組織,由@StevenRobbins,雖然是undervoted,然後埋在其他答案 – 2013-04-19 08:04:32