3

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?

user983731
  • 31
  • 1
  • Shouldn't the data reside in the model? So when switching ViewModels you only have to make sure they access the same model file. This could be done by static access, a factory.. – SvenG Oct 07 '11 at 10:35

1 Answers1

1

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.

Jevgenij Nekrasov
  • 2,690
  • 3
  • 30
  • 51