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?
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).
In C# 7 and above you could squeeze it even further:
private string _p = "";
public string P
{
get => _p;
set => Set(ref _p, value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With