我的问题几乎与以下现有问题相似: When nesting properties that implement INotifyPropertyChanged must the parent object propogate changes?
我的问题是如果我有以下三个级别 人 联系 地址
public class Address : INotifyPropertyChanged
{
string m_city;
public string City
{
get { return m_city; }
set
{
m_city = value;
NotifyPropertyChanged(new PropertyChangedEventArgs("City"));
}
}
}
public class Contact : INotifyPropertyChanged
{
Address m_address;
public Address Address
{
get { return m_address = value; }
set
{
m_address = value;
NotifyPropertyChanged(new PropertyChangedEventArgs("Address"));
}
}
}
public class Person : INotifyPropertyChanged
{
Contact m_contact;
public Contact ContactInfo
{
get { return m_contact = value; }
set
{
m_contact = value;
NotifyPropertyChanged(new PropertyChangedEventArgs("ContactInfo"));
}
}
}
我有一个包含联系人用户控件的用户控件。 当我更改城市时,它会调用地址类中city属性的notifyPropertychanged。和它 既不会调用Contact类下的Address setter,也不会调用Person类下的Contact setter。 如何在城市房产变更时通知人员班级?
答案 0 :(得分:0)
如果他们对使用它感兴趣,其他课程必须注册到地址的PropertyChanged
事件
例如,如果对象引用发生更改,Contact
只会在PropertyChanged
上引发Address
个事件,例如设置Address = new Address()
或Address = null
。它并不关心Address的属性,这是正确的。如果您希望它关注属性,请在PropertyChange
上挂钩Address.PropertyChanged
事件以引发Contact.Address
PropertyChange事件
public class Contact : INotifyPropertyChanged
{
Address m_address;
public Address Address
{
get { return m_address = value; }
set
{
// Remove old PropertyChanged notification if it existed
if (m_address != null)
m_address.PropertyChanged -= Address_PropertyChanged;
m_address = value;
// Add new PropertyChanged notification if it existed
if (m_address != null)
m_address.PropertyChanged += Address_PropertyChanged;
NotifyPropertyChanged(new PropertyChangedEventArgs("Address"));
}
}
}
void Address_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "City")
NotifyPropertyChanged(new PropertyChangedEventArgs("Address"));
}
如果你想让事件冒泡到Person类,你必须对Person类做同样的事情。
另一种选择是使用某种消息传递系统,例如MVVM Light的Messenger
或Microsoft Prism的EventAggregator
。使用此系统,Address
类将在City
更改时广播事件,Person
类将订阅这些消息并使用您提供Address
的任何内容处理它们发送邮件的内容等于Person.Contact.Address