Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to raise property changed MVVMLight

Tags:

c#

mvvm

wpf

Created a project using MVVM Light. It is common for the ViewModels to have a lot of properties that look like this

class TestModel
{
    public string DisplayValue { get; set; }
}

class TestViewModel : ViewModelBase
{
    public string DisplayValue
    {
         private TestModel model = new TestModel();

         get
         {
              return model.DisplayValue;
         }
         set
         {
              if (model.DisplayValue != value)
              {
                   model.DisplayValue = value;
                   RaisePropertyChanged();
              }
         }
    }
}

Sometimes the property is not in the model and is backed by a local private field instead. This approach works fine, but there is a ton of boilerplate code. How can the code duplication be reduced?

Are there any better solutions than the one I proposed or is there something built into MVVM Light that I missed?

like image 795
Adam Avatar asked Dec 03 '22 22:12

Adam


1 Answers

My version of the boilerplate MVVM Light property looks like this:

private string _p = "";

public string P
{
  get { return _p; }
  set { Set(ref _p, value); }
}

which is pretty much the thinnest one can get, made possible through the use of Set function provided by the underlying ObservableObject class (you could use ViewModelBase too).

Edit

In C# 7 and above you could squeeze it even further:

private string _p = "";
public string P
{
  get => _p;
  set => Set(ref _p, value);
}
like image 124
dotNET Avatar answered Dec 17 '22 01:12

dotNET