使用通用ViewModel

时间:2016-07-05 10:16:21

标签: wpf generics mvvm

我有一个WPF MVVM应用程序,但我希望我的ViewModel是通用的。应用程序假设要做的是获取一些数据并对其进行CRUD操作,而不知道它在编译时获得的数据类型。所以我声明我的ViewModel是这样的:

public class GenericViewModel<T> where T : class
{

    private void ConstructorBase()
    {
        Type theType = typeof(T);
        Properties = theType.GetProperties().ToList();
    }

    public GenericViewModel(DbContext _dbContextInsert) //pravi novi repository na osnovu DbContexta
    {
        ConstructorBase();
        _R = new RepositoryGlobal<T>(_dbContextInsert);
    }


    public T newT { get; set; }
    public T selectedT { get; set; }
    public List<PropertyInfo> Properties { get; set; }
    private RepositoryGlobal<T> _R;

}

现在,忽略你在其中看到的几乎所有内容,唯一重要的是从未到达过构造函数。我将此ViewModel设置为主窗口的DataContext,如下所示:

InitializeComponent();
this.DataContext = new GenericViewModel<Person>(new PersonDbContext());

但是当我在ViewModel的构造函数中放置断点时,程序永远不会停止。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

依赖关系应该是抽象,而不是实现。

您的通用视图模型应创建自己的存储库,而应通过构造函数传入此依赖关系的实例。

public class GenericViewModel<T> where T : class
{
    protected readonly IRepository<T> _Repository;

    public GenericViewModel(IRepository<T> repository)
    {
        _Repository = repository;
    }

    ...
}

然后,您将创建一个存储库实例,如下所示:

DbContext context = new PersonDbContext();
IRepository<Person> personRepo = new PersonRepository(context);
GenericViewModel<Person> personViewModel = new GenericViewModel<Person>(personRepo);

在那里,您的View Model的依赖关系不再依赖于特定的实现,您的代码现在更适合于更改。更不用说更容易测试了。

相关问题