Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 790
user1577566 Avatar asked Nov 19 '25 14:11

user1577566


1 Answers

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();
        }
    }
}
like image 95
Scott Chamberlain Avatar answered Nov 22 '25 02:11

Scott Chamberlain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!