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

标签 c# wpf events properties

我想检查一个不属于我且未实现 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();
        }
    }
}

关于当外部类中的属性更改时 C# 引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794652/

相关文章:

c# - 如何在 Azure 上为不同的环境部署不同的应用程序设置

wpf - Caliburn.Micro带 Controller ?

wpf - 我需要知道演示模型中的窗口句柄

c# - 将滚动条添加到文本框

c# - ASP MVC 在不查询数据库的情况下填充下拉列表的方法

c# - 为什么在构造函数中抛出异常会导致空引用?

c# - 当它只有一个 App.config 时将 WCF 服务部署到 IIS

javascript - 如何在 IE 中的文档上触发 "onload"事件

javascript - 处理浏览器 'full screen' 事件时如何访问我的 Angular Controller ?

java - 为树中的节点添加 Action 监听器