【问题标题】:How to set data context where Views and View models in separate library如何在单独的库中设置视图和视图模型的数据上下文
【发布时间】:2017-06-12 22:25:35
【问题描述】:

我的项目是

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

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

【问题讨论】:

  • 阅读以视图模型为中心的设计。如果您的代码使用定位器,那么您应该尽早解决这个问题。

标签: wpf mvvm prism autowired viewmodellocator


【解决方案1】:

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

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

非常简单!

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

【讨论】:

  • 感谢您的花絮!非常感谢。
  • 试过这个 IUnityContainer _container = new UnityContainer(); ViewModelLocationProvider.SetDefaultViewModelFactory((type) => { return _container.Resolve(type); });它没有解析视图模型
  • 我在app.xaml.cs中添加了上面的代码,它触发了viewModel构造函数中的调试断点,你能分享一些例子
  • 如果您使用的是最新版本的 Prism,则无需手动设置 SetDefaultViewModelFactory。您所要做的就是确保您的约定返回要解析的正确类型。博文中有一个示例链接
【解决方案2】:

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

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

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) 是更好的选择,因为您的视图模型也可能具有容器可以提供的依赖项。

希望这会有所帮助。

【讨论】:

  • 如果他用 C# 创建视图,那就是设计缺陷。视图从模板中获取数据上下文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-22
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
相关资源
最近更新 更多