MVVM Light - ViewModel reusage

937 views Asked by At

I'm using Pivot Control in Windows Phone 8 and i'm using MVVM Light.

I have created an UserControl that will be the content of each PivotItem, and a ViewModel that my UserControl should use.

For instance:

    ObservableCollection<PivotItem> Pivots = new ObservableCollection<PivotItem>();
    for (i = 0; i < length; i++) {
       Pivots.Add(new PivotItem() { Content = new MyUserControl() });
    }

and typically in my UserControl constructor i have something like this (which i think it's not a good pratice?):

    DataContext = new ViewModelLocator().MyViewModel;

This ViewModel will fetch data from a Database based on a position key. My question is how do I pass that key to MyViewModel and not making MyViewModel Singleton?

1

There are 1 answers

2
Martin Zikmund On BEST ANSWER

First of all – you shouldn't create new instances of ViewModelLocator. There is one root one, that is automatically added to your App.xaml page in the App.Resources element. You can reference it in XAML as {StaticResource Locator} or as App.Resources["Locator"] in code.

Secod issue – as you have multiple pivots and want multiple distinct View Model instances, the best thing you could probably do is to NOT add the MyViewModel view model in the ViewModelLocator and just create it there on the fly. This way you will not have it as a singleton and that is exactly what you want. You won't lose any MVVM Light functionality this way, just will need to recreate and refetch the data each time the controls are created.

If the "keys" you use to fetch the data are from a constrained set however (so there will be something like 5 of them not 100) and want to have the data keep loaded after the first load, you can register the MyViewModel in the ViewModelLocator's constructor normally

SimpleIoc.Default.Register<MyViewModel>();

And then in the code use the following syntax:

SimpleIoc.Default.GetInstance<MyViewModel>( "somekeyvalue" );

This will compare the supplied key value with SimpleIoc's internal dictionary of existing viewmodels and in case it already exists will return the existing instance, otherwise will create a new one and store it under the key for future reuse.