user1577566
user1577566

Reputation: 95

C# raise event when property changes in foreign class

I want to check if property changed in a class which isn't mine and doesn't implement INotifyPropertyChanged. This class is a part of an API and I want to raise event when Name property changes.

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

I want to use it in WPF by the way (treeView). Is there any way to do that?

Or am I out of luck if that class (Something in example above) doesn't implement INotifyPropertyChanged?

Upvotes: 3

Views: 3526

Answers (1)

Scott Chamberlain
Scott Chamberlain

Reputation: 127543

Unfortunately due to your constrains your only option is poling to see if the data has changed.

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

Upvotes: 2

Related Questions