繁体   English   中英

C# 在外部类中的属性更改时引发事件

[英]C# raise event when property changes in foreign class

我想检查一个不是我的并且没有实现 INotifyPropertyChanged 的​​类中的属性是否发生了变化。 此类是 API 的一部分,我想在 Name 属性更改时引发事件。

class SomethingChanged : INotifyPropertyChanged
{
    Something sth;
    string Name { get; set; }
    public SomethingChanged(Something Sth)
    {
        sth = Sth;
        Name = sth.Name;
        //do something to allow raise PropertyChangedEvent when sth.Name changes
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

顺便说一下,我想在 WPF 中使用它(treeView)。 有没有办法做到这一点?

或者,如果该类(上面示例中的某些内容)没有实现 INotifyPropertyChanged,我会走运​​吗?

不幸的是,由于您的限制,您唯一的选择是查看数据是否已更改。

sealed class SomethingChanged : INotifyPropertyChanged, IDisposable
{
    private Something sth;
    private string _oldName;
    private System.Timers.Timer _timer;

    public string Name { get { return sth.Name; }

    public SomethingChanged(Something Sth, double polingInterval)
    {
        sth = Sth;
        _oldName = Name;
        _timer = new System.Timers.Timer();
        _timer.AutoReset = false;
        _timer.Interval = polingInterval;
        _timer.Elapsed += timer_Elapsed;
        _timer.Start();
    }

    private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
    {
        if(_oldName != Name)
        {
           OnPropertyChanged("Name");
           _oldName = Name;
        }

        //because we did _timer.AutoReset = false; we need to manually restart the timer.
        _timer.Start();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        var tmp = PropertyChanged; //Adding the temp variable prevents a NullRefrenceException in multithreaded environments.
        if (tmp != null)
            tmp(this, new PropertyChangedEventArgs(propertyName));
    }

    public void Dispose()
    {
        if(_timer != null)
        {
            _timer.Stop();
            _timer.Dispose();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM