user2529011
user2529011

Reputation: 743

Raising property changed event for an object in another class not working

In my WPF application I have two properties, each one in different classes (ClassA & ClassB respectively). My desired output is that when I changed the property value in ClassA, if I go to the view that references ClassB that I should see that same change being reflected. But that is not my actual result. Instead, my logical error is that the property in ClassB is not getting updated.

This is how I have my two classes set up

public class ClassA : INotifyPropertyChanged
{
   #region [Property Change]
    
   public event PropertyChangedEventHandler PropertyChanged;
    
   private void RaisePropertyChanged([CallerMemberName] string caller = "")
   {
       if(PropertyChanged != null)
       {
           PropertyChanged(this, new PropertyChangedEventArgs(caller));
       }
    }
    #endregion [Property Change]
    
    public string Property_A
    {
       get => property_A;
       set
       {
          property_A = value;
          RaisePropertyChanged(nameof(Property_A));
          RaisePropertyChanged("Property_B"); // not working...
       }
    }
    private string property_A;
}

Meanwhile in ClassB.cs

public class ClassB : INotifyPropertyChanged
{
   #region [Property Change]
    
   public event PropertyChangedEventHandler PropertyChanged;
    
   private void RaisePropertyChanged([CallerMemberName] string caller = "")
   {
       if(PropertyChanged != null)
       {
           PropertyChanged(this, new PropertyChangedEventArgs(caller));
       }
    }
    #endregion [Property Change]

    private ClassA ClassAObject;

    public string Property_B
    {
       get => ClassAObject.Property_A;
    }
    
    publicClassB()
    {
       ClassAObject = new ClassA();
    }
}

I debug and see that when the string value of Property_A changes its going in the setter and although the code reaches the RaisePropertyChanged("Property_B") Its not being fired in ClassB. Can anyone see what I'm doing wrong?

Upvotes: 0

Views: 1757

Answers (1)

Xerillio
Xerillio

Reputation: 5259

To propagate changes happening in a "child" component, you would need to subscribe to the child's PropertyChanged event as suggested in this answer.

In your case that could look something like:

public class ClassB : INotifyPropertyChanged
{
   // stuff left out for brevity
    
    public ClassB()
    {
        ClassAObject = new ClassA();

        // Subscribe to ClassAObject's event and let subscribers of
        // ClassB know that something changed
        ClassAObject.PropertyChanged += (sender, eventArgs) =>
        {
            RaisePropertyChanged(nameof(Property_B));
        };
    }
}

Upvotes: 1

Related Questions