我正在寻找将 ViewModel 注入(inject) Shell View 的最佳方法。
我正在使用 Autofac(但如果有示例,我可以采用来自其他 IoC 容器的代码)。我已经正确注入(inject)了其他 VM - 但是使用 App 类的 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 绑定(bind)时有用):
public ShellViewModel ViewModel => DataContext as ShellViewModel;
现在,您只需在创建 Shell 时传递 ViewModel 类的实例,将其从 IoC 容器中拉出。在VS2017最新的Template 10模板中,应该在
CreateRootElement
App类的方法: 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()),
};
}
当然替换
new ShellViewModel()
使用代码从 Autofac 中提取它。
关于mvvm - Template10 MVVM IoC 将 ViewModel 注入(inject) Shell View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44837247/