Reputation: 1372
How can I listen in class B to the PropertyChanged
events from class A? I would like to listen to changes of a property from class A.
class A : INotifyPropertyChanged
{
private int _x;
public int X
{
get => _x;
set
{
if (_x == value) return;
_x = value;
OnPropertyChanged(nameof(X));
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
class B
{
public B(int x)
{
// In this class I want to listen to changes of the property X from class A
}
}
Upvotes: 3
Views: 4923
Reputation: 1322
Just listen to the event:
class B
{
public A _myA;
public B(int x)
{
_myA = new A();
_myA.PropertyChanged += A_PropertyChanged;
}
private void A_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName != nameof(_myA.X)) return;
}
}
Upvotes: 10