Template10 MVVM IoC 将 ViewModel 注入 Shell 视图

Template10 MVVM IoC Inject ViewModel into Shell View

我正在寻找将 ViewModel 注入 Shell 视图的最佳方法。

我正在使用 Autofac(但如果有示例,我可以采用来自其他 IoC 容器的代码)。我已经让其他 VM 正确注入 - 但是使用 App class.

的 ResoleForPage 方法解析 VM 的方法

我是 UWP 开发的新手,非常感谢任何帮助!

将 ViewModel 传递给 Shell 确实比传递给其他页面更简单,因为 Shell 是我们明确创建的唯一页面:因此,它应该足够了向类型为 ShellViewModel:

的 Shell 的构造函数添加参数
    public Shell()
    {
        Instance = this;
        this.InitializeComponent();
    }

    public Shell(INavigationService navService, ShellViewModel model) : this()
    {
        navigationMenu.NavigationService = navService;
        navigationMenu.RefreshStyles(App.Current.RequestedTheme, true);
        this.DataContext = model;
    }

然后以强类型方式公开 DataContext,与任何其他页面一样(主要用于在 xaml 中使用 x:Bind 绑定):

    public ShellViewModel ViewModel => DataContext as ShellViewModel;

现在您只需在创建 Shell 时传递 ViewModel class 的实例,将其从 IoC 容器中拉出。在VS2017最新的Template 10模板中,应该在App的CreateRootElement方法中class:

    public override UIElement CreateRootElement(IActivatedEventArgs e)
    {
        var service = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
        return new Template10.Controls.ModalDialog
        {
            DisableBackButtonWhenModal = true,
            Content = new Shell(service, new ShellViewModel()),
        };
    }

当然要用从 Autofac 中提取它的代码替换 new ShellViewModel()