Search code examples
c#wpfmvvmprism-6

How to set a DataContext of multiple Views to one instance of ViewModel


I'm using a ViewModelLocator for my Views, it is configured in Bootstrapper with following method:

protected override void ConfigureViewModelLocator()
{
    base.ConfigureViewModelLocator();

    ViewModelLocationProvider.Register<ViewA, ViewABViewModel>();
    ViewModelLocationProvider.Register<ViewB, ViewABViewModel>();
}

It works fine, but makes two separate instances of a ViewModel for my 2 Views. I want my both Views to use the same instance of a ViewModel.


Solution

  • Checking the source code shows the problem of creating a new instance for every view by default:

    static Func<Type, object> _defaultViewModelFactory = type => Activator.CreateInstance(type);
    

    Prism allows to define this method generally for all types or only special types. Second case should be preferred.

    ViewModelLocationProvider.Register<ViewA, ViewABViewModel>();
    

    only links the types of View and ViewModel together, no factory is defined. This means a new instance is created for each View. To use an instance at multiple views you need to define the factory method. Create one instance of your ViewModel

    ViewABViewModel vm = new ViewABViewModel();
    

    and register the factory methods for your Views by returning this already prepared instance

    ViewModelLocationProvider.Register<ViewA>(() => vm);
    ViewModelLocationProvider.Register<ViewB>(() => vm);
    

    Prism is now taking this instance instead of creating a new one.