Home > front end >  WPF bind to custom class with INotifyPropertyChanged
WPF bind to custom class with INotifyPropertyChanged

Time:06-22

Im working on a wpf application and I try to notify Parent class when Child's property is changed. Classes relations look like above:

class Class1
{
    Class2 c2;
    private void OnPropertyChanged()
    {
        // Do someting When Class3.Property is changed
    }
}

class Class2
{
    Class3 c3;
}

class Class3
{
     string Property
     {
         get {...}
         set
         {
          ...
          PropertyChanged();
         } 
     }
}

I know that there is INotifyPropertyChanged for this purposes, but I've found only the cases where it is used for binding .xaml files. Is there any way to bind custom classes with it, or with similar thing

CodePudding user response:

You can't bind simple classes unless the target is a DependencyObject (which is quite uncommon for non GUI related classes).

If you need simple notification, you would usually implement an event for the particular property or properties:

class ClassA
{
  public ClassA()
  {
    var classB = new ClassB();
    classB.Activated  = OnActivated;
  }

  private void OnActivated(object sender, EventArgs e)
  {
    // Handle event
  }
}
class ClassB
{
  public bool IsActivated 
  { 
    get => this.isActivated; 
    private set
    {
      this.isActivated = value;
      if (this.IsActivated)
      {
        OnActivated();
      }
      else
      {
        OnDeactivated();
      }
    }
  }

  public event EventHandler Activated;
  public event EventHandler Deactivated;

  private void OnActivated()
    => this.Activated?.Invoke();

  private void OnDeactivated()
    => this.Deactivated?.Invoke();
}
  • Related