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?
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}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With