我需要在代码中定义新的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事件,但不会更新文本块.谁能告诉我为什么?
谢谢,本
它的根源是我传递给PropertyChangedEventArgs的字符串与该属性的名称不完全匹配.我有这样的事情:
public int HouseNumber { get { return _houseNumber; } set { _houseNumber = value; NotifyPropertyChanged("HouseNum"); } }
它应该在哪里:
public int HouseNumber { get { return _houseNumber; } set { _houseNumber = value; NotifyPropertyChanged("HouseNumber"); } }
哎呀!感谢您向正确的方向努力.