【问题标题】:How to keep Views and ViewModels in seperate NameSpaces (, and assemblies) in Stylet如何在 Stylet 中将视图和视图模型保存在单独的命名空间(和程序集)中
【发布时间】:2020-12-10 03:06:45
【问题描述】:

我已经开始在 WPF 中为 MVVM 使用Stylet。我在命名空间StyletProj.Pages 中有我的视图 在命名空间StyletProj 中使用Bootstrapper,在命名空间StyletViewModels.ViewModels 中使用我的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(和wiki page),但他们建议创建一个全新的ViewManager 来执行此操作,这似乎有点矫枉过正。我该如何以最简单的方式解决这个问题(我宁愿不创建新的ViewManager?我什至不明白他们在示例中做了什么。

【问题讨论】:

    标签: c# wpf mvvm stylet


    【解决方案1】:

    您不必创建新的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.
    }
    

    您可以将键值对添加到 NamspaceTransformations 字典。命名空间转换所做的基本上是将与字典中条目的键匹配的视图模型类型名称的前缀替换为其值。换句话说,如果你在命名空间A 中传递一个视图模型,则在命名空间B 中搜索相应的视图。

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

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

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

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

    【讨论】:

    • 嗨!感谢所有帮助,这似乎更有意义。我的应用程序仍然无法运行,当我运行时出现此错误Unhandled exception. StyletIoC.StyletIoCRegistrationException: No registrations found for service ShellViewModel. 这是我的 BootStrapper { public class BootStrapper : Bootstrapper&lt;ShellViewModel&gt; { protected override void Configure() { var viewManager = Container.Get&lt;ViewManager&gt;(); viewManager.NamespaceTransformations.Add("StyletViewModels.ViewModels", "StyletProj.Views"); } } }
    • @rzk3 你得到这个异常,因为容器不知道其他程序集中的类型,你要么必须将每个类型绑定到容器或注册程序集,请参阅我的编辑。另外,StyletProj.Views 不应该是StyletProj.Pages吗?
    • 发现问题,我需要绑定ViewModel 程序集而不是View 程序集。还要注意,请确保它是程序集名称而不是命名空间名称,否则您将获得 IO 异常。非常感谢您的帮助!
    猜你喜欢
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 1970-01-01
    相关资源
    最近更新 更多