Why is the view constructor not called every time I create a new view model?

I am using WPF with the model-view-viewmodel template. I have ResultsView and ResultsViewModel that are related as follows:

<DataTemplate DataType="{x:Type VM:ResultsViewModel}"> <VW:ResultsView/> </DataTemplate> 

In my main window, I have some kind of page setup where the MainContent property stores the current page (an instance of ViewModel).

I create the page as follows

 MainContent = new ResultsViewModel(); 

ResultsView is based on UserControl, it also has a handler for the Loaded event, which performs some user interface initialization operations.

Everything works fine when the user moves between different pages.

But if the user opens the ResultsView line twice, the ResultsView constructor references not for the second time, and the Loaded event is not raised. It looks like I now have the same old instance of ResultsView that is bound to the new ResultsViewModel ()!

Why doesn't WPF create a new view every time I create a new ViewModel? Is there a way to force WPF to abandon the old view if the old view model is destroyed?

+1
source share
2 answers
 <DataTemplate x:Shared="False" DataType="{x:Type VM:ResultsViewModel}"> <VW:ResultsView/> </DataTemplate> 
+8
source

See Kent's answer for practical work on your issue.

However, it is good practice to create an instance of a view only once, since there is overhead associated with building a visual tree and setting up all the bindings. As a rule, the View / ViewModel should be designed in such a way that you can change the underlying ViewModel without viewing the View or even notice (except for changing the DataContext and, therefore, all the binding values ​​are being reviewed.) If you currently have logic in your loaded event , getting ready for a specific ViewModel, consider registering to be notified when the DataContext changes (see this example ).

+2
source

Source: https://habr.com/ru/post/1394491/


All Articles