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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…