MVVM and INotifyPropertyChanged Issue

前端 未结 3 409
我寻月下人不归
我寻月下人不归 2021-01-15 04:50

I have a big problem with MVVM design. I am trying to catch every PropertyChanged of my inner nested objects, including futhermore propertchanged of their nested objects, in

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-15 05:41

    There is no clear constraint about what PropertyName should contains in PropertyChangedEventArgs.

    See Subscribe to INotifyPropertyChanged for nested (child) objects.

    Here is an example :

    class A : BaseObjectImplementingINotifyPropertyChanged {
    
      private string m_name;
      public string Name {
        get { return m_name; }
        set {
          if(m_name != value) {
            m_name = value;
            RaisePropertyChanged("Name");
          }
        }
      }
    }
    
    class B : BaseObjectImplementingINotifyPropertyChanged {
    
      private A m_a;
      public A A {
        get { return m_a; }
        set {
          if(m_a != value) {
            if(m_a != null) m_a.PropertyChanged -= OnAPropertyChanged;
            m_a = value;
            if(m_a != null) m_a.PropertyChanged += OnAPropertyChanged;
            RaisePropertyChanged("A");
          }
        }
      }
    
      private void OnAPropertyChanged(object sender, PropertyChangedEventArgs e) {
        RaisePropertyChanged("A." + e.PropertyName);
      }
    
    }
    
    
    B b = new B();
    b.PropertyChanged += (s, e) => { Console.WriteLine(e.PropertyName); };
    b.A.Name = "Blah"; // Will print "A.Name"
    

提交回复
热议问题