如何在 Stylet 中将视图和视图模型保存在单独的命名空间(和程序集)中

How to keep Views and ViewModels in seperate NameSpaces (, and assemblies) in Stylet

我已经开始在 WPF 中使用 Stylet 的 MVVM。我在命名空间 StyletProj.Pages 中有我的视图 在命名空间 StyletProj 中使用 Bootstrapper,在命名空间 StyletViewModels.ViewModels 中使用我的 ViewModel(在另一个程序集中)。我需要链接 Views 和 ViewModels。我怎样才能做到这一点?这就是我目前在我的引导程序中所拥有的。

namespace StyletProj
{
    public class Bootstrapper : Bootstrapper<ShellViewModel>
    {
        protected override void ConfigureIoC(IStyletIoCBuilder builder)
        {
            // Configure the IoC container in here
        }

        protected override void Configure()
        {
            // Perform any other configuration before the application starts
            var viewManage = this.Container.Get<ViewManager>();
            viewManage.NamespaceTransformations
        }
    }
}

我可以用 NamespaceTransformations 做什么?这是错误的方法吗?我也发现了这个 example (and wiki page),但他们建议创建一个全新的 ViewManager 来执行此操作,这似乎有点矫枉过正。我如何以最简单的方式解决这个问题(我宁愿不创建新的 ViewManager?我什至不明白他们在示例中做了什么。

您不必创建新的 ViewManager,因为已经支持此方案。

您只需将名称空间转换添加到 ViewManager,将视图模型从 StyletViewModels.ViewModels 名称空间映射到 StyletProj.Pages 名称空间的视图。

protected override void Configure()
{
   var viewManager = Container.Get<ViewManager>();
   viewManager.NamespaceTransformations.Add("StyletViewModels.ViewModels", "StyletProj.Pages");

   // ...other configuration code.
}

您可以将 key-value 对添加到 NamspaceTransformations 字典中。命名空间转换所做的基本上是用它的值替换与字典中条目的键匹配的视图模型类型名称的前缀。换句话说,它表示如果您在命名空间 A 中传递视图模型,请在命名空间 B.

中搜索相应的视图

关于使用容器的附注。当您在其他程序集中有类型时,您需要注册它们,以便容器知道它们并可以实例化它们。您可以引用程序集并手动绑定目标 类 例如:

builder.Bind<MyViewModel>().ToSelf();

但是,注册程序集更容易,因此容器可以自动发现所有类型。我假设示例程序集称为 StyletViewModels.ViewModels:

builder.Assemblies.Add(Assembly.Load("StyletViewModels.ViewModels"));