更多细节 - 当嵌套实现INotifyPropertyChanged的属性时,父对象传播必须更改吗?

时间:2011-12-22 20:04:55

标签: wpf user-controls inotifypropertychanged

我的问题几乎与以下现有问题相似: 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。 如何在城市房产变更时通知人员班级?

1 个答案:

答案 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