为什么每次创建新的视图模型时视图构造函数都不会被调用?
我使用WPF与model-view-viewmodel模式。我有一个ResultsView和ResultsViewModel这样连接:
I am using WPF with model-view-viewmodel pattern. I have a ResultsView and ResultsViewModel which are connected like this:
<DataTemplate DataType="{x:Type VM:ResultsViewModel}">
<VW:ResultsView/>
</DataTemplate>
在我的主窗口中我有一些分页设置,其中MainContent属性存储当前页面(ViewModel实例)。
In my main window I have some kind of paged setup where MainContent property stores the current page (ViewModel instance).
我创建这样的页面
MainContent = new ResultsViewModel();
ResultsView基于UserControl,它还有一个Loaded事件的处理程序,它负责一些UI初始化。
ResultsView is based on UserControl, it also has a handler for Loaded event which does some UI initialization stuff.
当用户在不同页面之间导航时,一切都正常。
Everything works fine while the user is navigating between different pages.
但如果用户打开ResultsView次,则ResultsView构造函数不第二次调用,并且Loaded事件也不会被调用。看起来现在我有相同的旧的ResultsView实例附加到新的ResultsViewModel()!
But if the user opens the ResultsView two times in a row, the ResultsView constructor is not called the second time, and also Loaded event is not called. It seems that now I have the same old ResultsView instance attached to the new ResultsViewModel()!
为什么WPF不创建一个新的View每次创建一个新的ViewModel?如果旧的视图模型被销毁,是否有一些方法可以强制WPF舍弃旧视图?
<DataTemplate x:Shared="False" DataType="{x:Type VM:ResultsViewModel}">
<VW:ResultsView/>
</DataTemplate>