1

in .NET (and WPF), I need to monitor changes on a Timespan object which doesn't include any change event like PropertyChanged. What would be the best way to add this functionnality?

742
  • 3,009
  • 3
  • 23
  • 18

1 Answers1

4

Assuming you are exposing the Timespan as a property of a class, you can implement INotifyPropertyChanged like this:

public class MyClass : INotifyPropertyChanged
{
    private Timespan _timespan;

    public event PropertyChangedEventHandler PropertyChanged;

    public Timespan Timespan
    {
        get { return _timespan; }
        set
        {
            Timespan oldValue = _timespan;
            _timespan = value;

            if(oldValue != value)
                OnPropertyChanged("Timespan");
        }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler @event = PropertyChanged;

        if(@event != null)
            @event(
                this, 
                new PropertyChangedEventArgs(propertyName ?? string.Empty)
                );
    }
}

Any assignment of a changed value to the property Timespan will raise the expected event.

Paul Turner
  • 38,949
  • 15
  • 102
  • 166