我正在使用MVVMLight创建一个应用程序。
在我的应用程序中,我有一个"Catalog“视图和一个Downloads视图,每个视图都与它自己的ViewModel相关联,这些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中的集合,但是只有当用户首次打开下载视图时,它才能工作。在另一种情况下,还没有创建下载视图模型,而消息也没有结果。
有办法在应用程序启动时调用Downdload的构造函数吗?还是应该使用专用类来存储我的下载列表?
发布于 2016-06-18 16:51:45
在应用程序生命周期的早期获取视图模型的一个实例,因为服务定位器将在其缓存中保存视图模型的一个实例。
public class ViewModelLocator {
static ViewModelLocator() {
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<CatalogViewModel>();
SimpleIoc.Default.Register<CreatorViewModel>();
SimpleIoc.Default.Register<DownloadsViewModel>();
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
//Default instance
//Done so an instance will be generated and held in cache
var defaultDownloadsViewModel = ServiceLocator.Current.GetInstance<DownloadsViewModel>();
}
public ViewModelLocator(){
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>();
}
}
private void NotifyUserMethod(NotificationMessage message )
{
MessageBox.Show(message.Notification);
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}https://stackoverflow.com/questions/37899121
复制相似问题