-1

I have the code pattern below repeated numerous times throughout my WPF application's view models. Is there any quick and easy way to reduce it, without resorting to aspect oriented programming or the like?

private string _scriptExecutionStage;
public string ScriptExecutionStage
{
    get => _scriptExecutionStage;
    set
    {
        if (value != _scriptExecutionStage)
        {
            _scriptExecutionStage = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ScriptExecutionStage"));
        }
    }
}
sipsorcery
  • 30,273
  • 24
  • 104
  • 155

2 Answers2

1

You can - indeed - reduce the boilerplate code for properties. Alas, this does not come without cost, which is deriving your viewmodels from a ViewModelBase class

public class ViewModelBase : INotifyPropertyChanged
{
    protected void SetValue<T>(ref T field, T value, [CallerMemberName] string propertyName = null)
    {
        if (AreEqual(field, value))
        {
            return;
        }

        field = value;
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

In your ViewModelBase class you can define the SetValue method as presented. Basically you pass the reference to your backing field and operate with this reference. The logic stays the same.

In your property you can now just do

public string ScriptExecutionStage
{
    get => _scriptExecutionStage;
    set => SetValue(ref _scriptExecutionStage, value);
}
Clemens
  • 123,504
  • 12
  • 155
  • 268
Paul Kertscher
  • 9,416
  • 5
  • 32
  • 57
1

You could create an SetProperty<T>(...) in your ViewModelBase like.

    protected void SetProperty<T>(ref T propertyToSet, T value, [CallerMemberName]string propertyName=null)
    {
        if(!propertyToSet.Equals(value))
        {
            propertyToSet = value;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
Clemens
  • 123,504
  • 12
  • 155
  • 268
3xGuy
  • 2,235
  • 2
  • 29
  • 51