我正在使用MVVM Toolkit。 在我的ViewModels中,我保留了将ViewModel切换到另一个时我想保存的数据。
负责切换ViewModel的是ViewModelLocator:
http://simplemvvmtoolkit.codeplex.com/wikipage?title=Getting%20Started第8点。
ViewModelLocator每次都返回新的ViewModel:
public class ViewModelLocator
{
// Create ProductListViewModel on demand
public ProductListViewModel ProductListViewModel
{
get
{
IProductServiceAgent serviceAgent = new MockProductServiceAgent();
return new ProductListViewModel(serviceAgent);
}
}
}
我不想打破MVVM规则。我正在考虑创建这样的新对象:
public class ViewModelLocator
{
private ProductListViewModel productListViewModel;
// Create ProductListViewModel on demand
public ProductListViewModel ProductListViewModel
{
get
{
IProductServiceAgent serviceAgent = new MockProductServiceAgent();
if (productListViewModel == null)
productListViewModel = new ProductListViewModel(serviceAgent);
return productListViewModel;
}
}
}
...或在切换ViewModel序列化ViewModel时,将其加载回来时 - 反序列化......
这个问题的正确解决方案是什么?
答案 0 :(得分:1)
我建议您使用任何类型的IoC容器(例如Unity)
public class ViewModelLocator
{
public static UnityContainer Contaner { get; private set;}
static ViewModelLocator()
{
Container = new UnityContainer();
Container.RegisterType<ProductListViewModel>(new ContainerControlledLifetimeManager());
}
public ProductListViewModel ProductViewModel
{
get
{
return Container.Resolve<ProductListViewModel>();
}
}
}
我认为在MVVM Light Toolkit中你有SimpleIoc - 轻量级的IoC容器实现。