4

Sometimes I need to raise propertychanged for a related property, like this:

public bool IsValid
    {
        get { return _isValid; }
        set
        {
            if (value.Equals(_isValid)) return;
            _isValid = value;
            OnPropertyChanged("IsValid");
            OnPropertyChanged("IsSavable");
        }
    }

I could write it like this:

public bool IsValid
    {
        get { return _isValid; }
        set
        {
            if (value.Equals(_isValid)) return;
            _isValid = value;
            this.RaisePropertyChanged("IsValid");
            this.RaisePropertyChanged("IsSavable");
        }
    }

Code based on Paul's answer:

    public ViewModelBase()
    {
        Validator = new AlwaysTrueValidValidator<ViewModelBase>();
        // logic for IsSavable
        this.WhenAny(x => x.IsValid, x => x.IsDirty, x => x.IsBusy, (valid, dirty, busy) => valid.Value && dirty.Value && busy.Value == false)
            .ToProperty(this, x => x.IsSavable, out _isSavable);
    }

    readonly ObservableAsPropertyHelper<bool> _isSavable;
    public bool IsSavable
    {
        get { return _isSavable.Value; }
    }

    [UsedImplicitly]
    public bool IsValid
    {
        get { return _isValid; }
        set { this.RaiseAndSetIfChanged(ref _isValid, value); }
    }

    public void OnPropertyChanged(string property)
    {
        // ReSharper disable once ExplicitCallerInfoArgument
        this.RaisePropertyChanged(property);
    }

As you can see the code is a lot cleaner it's all get/set and the logic is in one place.

Is there a smarter way to do it? Yes

Martin Andersen
  • 2,460
  • 2
  • 38
  • 66

1 Answers1

5

In ReactiveUI, the desire to do this means that you are Doing It Wrong (or at least, not the RxUI way). IsSaveable is related to IsValid, you should describe that using WhenAny and ToProperty. Maybe you could write that as:

this.WhenAny(x => x.IsValid, x => x.IsChanged, (valid, changed) => valid.Value && changed.Value)
    .ToProperty(this, x => x.IsSavable, out isSavable);
Ana Betts
  • 73,868
  • 16
  • 141
  • 209