An example of a ‘ViewModelBase’ class, that implements INotifyPropertyChanged.

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    protected virtual bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = "")
    {
        if (EqualityComparer<T>.Default.Equals(storage, value))
            return false;
        storage = value;
        this.OnPropertyChanged(propertyName);
        return true;
    }
}

And use it like this:

private string _totalTime;
public string TotalTime
{
    get { return _totalTime; }
    set
    {
        if (_totalTime != value)
        {
            _totalTime = value;
            OnPropertyChanged();
        }
    }
}

... or even:

private string _totalTime;
public string TotalTime
{
    get { return _totalTime; }
    set { SetProperty(ref _totalTime, value); }
}

As always, feel free to comment, or ask.

 


Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading