【发布时间】:2016-06-18 16:20:27
【问题描述】:
我正在使用 MVVMLight 创建一个应用程序。
在我的应用程序中,我有一个“目录”视图和一个 Downloads 视图,每个视图都与它自己的 ViewModel 相关联,它们在 ViewModelLocator 中声明:
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<CatalogViewModel>();
SimpleIoc.Default.Register<CreatorViewModel>();
SimpleIoc.Default.Register<DownloadsViewModel>();
Messenger.Default.Register<NotificationMessage>(this, NotifyUserMethod);
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public CatalogViewModel Catalog
{
get
{
return ServiceLocator.Current.GetInstance<CatalogViewModel>();
}
}
public DownloadsViewModel Downloads
{
get
{
return ServiceLocator.Current.GetInstance<DownloadsViewModel>();
}
}
public CreatorViewModel Creator
{
get
{
return ServiceLocator.Current.GetInstance<CreatorViewModel>();
}
}
private void NotifyUserMethod(NotificationMessage message )
{
MessageBox.Show(message.Notification);
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
我计划使用消息传递将我的selectedCatalogItems 发送到下载 VM 中的集合,但它仅在用户首先打开下载视图时才有效。在另一种情况下,下载视图模型尚未创建,消息无处可去。
有没有办法在应用启动时调用 Download VM 的构造函数,还是应该使用专用类来存储我的下载列表?
【问题讨论】:
-
您还可以在应用程序的生命周期内注册视图模型的实例。这样,当您调用 get instance 时,您每次都会获得相同的视图模型。
-
听起来不错!您对如何实现这一目标有任何建议吗?由于我依赖于处理视图模型实例化的 mvvm light,因此我不知道应该在哪里以及如何调用视图模型的构造函数。
-
注册其他视图模型时的相同位置。 viewmodel 定位器有静态构造函数吗?您的 sn-p 相当脱节,所以无法分辨
-
这是我的定位器的构造函数,与 mvvm light 的默认构造相同,因此它不是静态的:public class ViewModelLocator { public ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register
(); SimpleIoc.Default.Register (); SimpleIoc.Default.Register (); }
标签: c# mvvm mvvm-light