我有一个带有一个属性的简单类,这个类实现了接口INotifyPropertyChange。
public class SomeClass : INotifyPropertyChanged
{
private string _iD;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public string ID
{
get { return _iD; }
set
{
if (String.IsNullOrEmpty(value))
throw new ArgumentNullException("ID can not be null or empty");
if (this.ID != value)
{
_iD = value;
NotifyPropertyChanged(ID);
}
}
}
}
我正在尝试将OneWay绑定到标签。我在后面的代码中设置了标签DataContext
。
private SomeClass _myObject;
public MainWindow()
{
InitializeComponent();
_myObject = new SomeClass() { ID = "SomeID" };
lb.DataContext = _myObject;
}
在XAML中,我将属性ID
绑定到标签的Content
。
<Label Name="lb" Content="{Binding Path = ID, Mode=OneWay}" Grid.Row="0"></Label>
<TextBox Name="tb" Grid.Row="1"></TextBox>
<Button Name="btn" Content="Change" Height="20" Width="100" Grid.Row="2" Click="btn_Click"></Button>
然后我在按钮点击事件中更改了属性ID
的值,但标签的内容没有改变。
private void btn_Click(object sender, RoutedEventArgs e)
{
_myObject.ID = tb.Text;
Title = _myObject.ID;
}
为什么这不起作用?
答案 0 :(得分:3)
NotifyPropertyChanged应该采用已更改属性的名称,而不是属性的值。因此,将NotifyPropertyChanged(ID)
更改为NotifyPropertyChanged("ID")
。