Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

mvvm

wpf

I am new to both WPF and MVVM and a came across an issue when attempting to set the DataContext to the same instance of my ViewModel in two separate views.

This was because:

<Window.DataContext>
    <local:ViewModel/>
</Window.DataContext>

would create a new instance of the view model for each view.

To get around this I decided to create a class that stored static instances of each ViewModel I used. Then in the cs file of each view I would then set the DataContext to the appropriate ViewModel from this static class.

This works but doesn't seem the best idea for larger programs where the multiple instances of the ViewModel may be needed simultaneously.

What are better approaches to this problem - Are there sound ways to have multiple Views using the same instance of a ViewModel?

Or is this approach bad practice - Should I be designing a program with one View for every ViewModel?

like image 379
Alfie Avatar asked Jul 26 '18 10:07

Alfie


1 Answers

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}"
like image 73
Fabulous Avatar answered Oct 22 '22 18:10

Fabulous