Reputation: 3
In a project C# WPF I started using the MVVM Community Toolkit and my question is about properties. Let's say I have a Model with some properties:
public class TheModel
{
public bool FirstProp {get; set;}
public int SecondProp {get; set;}
}
Then I have a Viewmodel with instance of that Model, usually I set properties like this:
public class TheViewModel : ObservableObject
{
private readonly TheModel _theModel;
public bool FirstProp
{
get => _theModel.FirstProp;
set
{
if (_theModel.FirstProp != value)
{
_theModel.FirstProp = value;
OnPropertyChanged();
}
}
}
public int SecondProp
{
get => _theModel.SecondProp;
set
{
if (_theModel.SecondProp != value)
{
_theModel.SecondProp = value;
OnPropertyChanged();
}
}
}
public TheViewModel(TheModel theModel)
{
_theModel = theModel;
}
}
My question: I wonder if there is a shorter way provided by MVVM Community toolkit to set properties (such as FirstProp and SecondProp) in the view model
The above code is working but if you have many properties it becomes boring to write them all
Upvotes: 0
Views: 943
Reputation: 6292
You can use the SetProperty method:
public bool FirstProp
{
get => _theModel.FirstProp;
set => SetProperty(_theModel.FirstProp, value, _theModel, (m, v) => m.FirstProp = v);
}
It makes the value check for you and calls OnPropertyChanged. Whether it's less code that the other I leave up to you.
Upvotes: 0