【问题标题】:Listening to PropertyChanged from another class从另一个类监听 PropertyChanged
【发布时间】:2020-08-26 07:11:56
【问题描述】:

如何在 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
        }
}

【问题讨论】:

    标签: c# .net event-handling


    【解决方案1】:

    只听事件:

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

    【讨论】:

    • 这将处理所有属性更改。 OP 对特定属性感兴趣。如何处理X属性的变化?
    • 抱歉。我将添加代码来检查属性
    • 您可以检查 EventArgs 以找出修改了哪个属性。用一个例子修改了我的答案
    • 我知道答案。我只是想指出你的回答并不完整。
    猜你喜欢
    • 2013-11-10
    • 2014-03-31
    • 1970-01-01
    • 2011-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多