在创建新的MVVM灯(WPF451)项目时,我获得了此示例代码,这让我感到困惑。
DataItem.cs:
public class DataItem
{
public string Title { get; private set; }
public DataItem(string title)
{
Title = title;
}
}
此类声明ViewModel中需要的一组属性。它在Model层DataService中使用,它在其构造函数中为VM提供数据。
DataService.cs
public class DataService : IDataService
{
public void GetData(Action<DataItem, Exception> callback)
{
// Use this to connect to the actual data service
var item = new DataItem("Welcome to MVVM Light");
callback(item, null);
}
}
我认为它也会在VM中用于保存属性,如下所示:
public DataItem Data { get; set; }
但是,MVVM light开发人员决定重新声明VM中的属性。
MainViewModel.cs:
public class MainViewModel : ViewModelBase
{
private readonly IDataService _dataService;
private string _welcomeTitle = string.Empty;
public string WelcomeTitle
{
get{ return _welcomeTitle; }
set{ Set(ref _welcomeTitle, value); }
}
public MainViewModel(IDataService dataService)
{
_dataService = dataService;
_dataService.GetData(
(item, error) =>
{
WelcomeTitle = item.Title;
});
}
}
我无法理解为什么他们这样实施。是的,它减少了多余的INotifyPropertyChanged实现对象,因此它使用的资源更少。但是,如果我必须为VM实现大量属性,我将不得不在VM和DataItem上编写属性,而且当我想添加或删除属性时,我将不得不编辑它们。
我不能只在VM中持有DataItem属性吗?或者我错过了什么?
答案 0 :(得分:1)
DataItem
只代表Model
。如果Model
是无法修改的实体(数据库自动生成的POCO),则此方案可行。
是的,您必须在Model
中拥有每个适用的ViewModel
属性,以便它可以RaisePropertyChanged,是的,这更像是“工作”,但它提供了两者之间的抽象。
有些人可以修改Model
以使其实施INotiftyPropertyChanged
,其他人则认为Model
不应该这样做,所有工作都应该在ViewModel
中完成(在这种情况下正在做的事情)。