在一个 C# WPF 项目中,我开始使用 MVVM Community Toolkit,我的问题是关于属性的。假设我有一个具有某些属性的模型:
public class TheModel
{
public bool FirstProp {get; set;}
public int SecondProp {get; set;}
}
然后我有一个带有该模型实例的 Viewmodel,通常我设置如下属性:
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;
}
}
我的问题:我想知道 MVVM Community 工具包是否提供了一种更短的方法来在视图模型中设置属性(例如 FirstProp 和 SecondProp)
上面的代码可以工作,但是如果你有很多属性,那么把它们全部写下来就变得很无聊
您可以使用SetProperty方法:
public bool FirstProp
{
get => _theModel.FirstProp;
set
{
SetProperty(ref _theModel.FirstProp, value)
}
}
它为您检查值并调用 OnPropertyChanged。