如何在单独的库中设置视图和视图模型的数据上下文

How to set data context where Views and View models in separate library

我的项目是

  1. student.shell.client
  2. student.views
  3. student.viewModels
  4. Modules.student

student.views 有 student.viewModels 引用,在 stuent.views 中使用 ViewModelLocator.AutoWireViewModel= true,它没有解析视图模型。在不同的项目中拥有视图和视图模型不是一个好习惯吗? 如何在此处连接视图和视图模型?

您真的需要视图和视图模型的单独程序集吗?可能不会。如果你想使用视图模型定位器,那么最简单的方法就是让它们在同一个 project/assembly 中。

要么,要么在后面的视图代码中新建视图模型。如果您的视图模型没有任何依赖项,这将可以正常工作。有些人对此不以为然,因为视图和视图模型之间的耦合相当紧密。

public partial class StudentView : UserControl
{
    public StudentView()
    {
        InitializeComponent();
        DataContext = new StudentViewModel();
    }
}

或者,您可以让 IoC 容器在视图构造函数中提供视图模型。

public partial class StudentView : UserControl
{
    public StudentView(StudentViewModel viewModel)
    {
        InitializeComponent();
        DataContext = viewModel;
    }
}

第二个选项 (IoC) 是更好的选择,因为您的视图模型也可能具有容器可以提供的依赖项。

希望对您有所帮助。

是的,您可以将 ViewModel 放在单独的程序集中,您只需告诉 ViewModelLocator 用于查找它们的新规则。在此博客中,您可以了解如何更改约定以使用您自己的约定:

http://brianlagunas.com/getting-started-prisms-new-viewmodellocator/

非常简单!

顺便说一句@R。 Richards,Prism 在自动解析 VM 时使用 DI,所有依赖项都将毫无问题地解析,并且不会注入 View ctor。这样,View 项目甚至不必引用 ViewModel 项目。只要将所有程序集都加载到 AppDomain 中,它就可以正常工作。