3

我想检查一个不是我的并且没有实现 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,我会不会走运?

4

1 回答 1

2

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

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();
        }
    }
}
于 2013-11-05T17:35:59.023 回答