gpt4 book ai didi

c# - 从另一个类(class)收听 PropertyChanged

转载 作者:行者123 更新时间:2023-12-05 09:08:22 25 4
gpt4 key购买 nike

我如何在 B 类中监听来自 A 类的 PropertyChanged 事件?我想听听 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
}
}

最佳答案

只听事件:

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;
}
}

关于c# - 从另一个类(class)收听 PropertyChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63592321/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com