开发者

Simple MVVM Toolkit - loosing ViewModel when switching them

开发者 https://www.devze.com 2023-04-11 15:37 出处:网络
I\'m using MVVM Toolkit. In my ViewModels I\'m keeping data which I\'d like to save when switching ViewModel to another.

I'm using MVVM Toolkit. In my ViewModels I'm keeping data which I'd like to save when switching ViewModel to another.

Responsible for switching ViewModels is ViewModelLocator:

http://simplemvvmtoolkit.codeplex.com/wikipage?title=Getting%20Started point 8.

ViewModelLocator everytime returns new ViewModel:

public class ViewModelLocator
{
    // Create ProductListViewModel on demand
    public ProductListViewModel ProductListViewModel
    {
   开发者_如何学运维     get
        {
            IProductServiceAgent serviceAgent = new MockProductServiceAgent();
            return new ProductListViewModel(serviceAgent);
        }
    }
}

I don't want to break MVVM rules. I was thinking about creating new objects like this:

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;
        }
    }
}

... or while switching ViewModel serialize ViewModel, when loading it back - deserialize...

What is the proper solution of this problem?


I will recommend you to use any type of IoC container for that (for example 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>();
        }
    }
}

I think in MVVM Light Toolkit you have SimpleIoc - lightweight implementation of IoC container.

0

精彩评论

暂无评论...
验证码 换一张
取 消