How to have multiple Views using the same ViewModel in MVVM?

You can instantiate that view model in App.xaml so that it is accessible to the whole application.

<Application.Resources>
    <local:ViewModel x:Key="sharedViewModel" />
</Application.Resources>

Then in your views when you want to use that datacontext, you do the following...

DataContext="{StaticResource sharedViewModel}"

Simple and easy as well as one of the recommended approach is implementing ViewModelLocator.

Idea is having defined all the ViewModels in ViewModelLocator class and access the ViewModel wherever needed. Using Same ViewModel in different View will not be a problem here.

    public class ViewModelLocator
{
         private MainWindowViewModel mainWindowViewModel;
  public MainWindowViewModel MainWindowViewModel
    {
        get
        {
            if (mainWindowViewModel == null)
                mainWindowViewModel = new MainWindowViewModel();

            return mainWindowViewModel;
        }
    }
    private DataFactoryViewModel dataFactoryViewModel;
 public DataFactoryViewModel DataFactoryViewModel
    {
        get
        {
            if (dataFactoryViewModel == null)
                dataFactoryViewModel = new DataFactoryViewModel();

            return dataFactoryViewModel;
        }
    }
}

App.xaml

    xmlns:core="clr-namespace:MyViewModelLocatorNamespace"

<Application.Resources>
    <core:ViewModelLocator x:Key="ViewModelLocator" />
</Application.Resources>

Usage

<Window ...
  DataContext="{Binding Path=MainWindowViewModel, Source={StaticResource ViewModelLocator}}">

refer : So Question codes copied from there.. as i cannot rip the codes from my project..


I had this same question and I couldn't find a good answer. After thinking about it for a while I came to the conclusion that in most cases it's best to create a one to one mapping between view model and view. So in this situation I would create two separate view models that inherit from a base view model. That way you can put whatever is common in the base view model and add any fields or methods that might be different to the more specific view model. If the view models truly are equivalent then you might want to ask yourself why you have two separate views in the first place. You may consider merging them into one view. It's possible that having two separate views is what you want, but it's just something to consider.

Tags:

C#

Wpf

Mvvm