Why the view constructor is not called every time

2019-06-07 06:57发布

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>

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

I create the page like this

MainContent = new ResultsViewModel();

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.

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()!

Why WPF does not create a new View each time I create a new ViewModel? Is there some way I can force WPF to discard the old view if the old viewmodel is destroyed?

2条回答
放荡不羁爱自由
2楼-- · 2019-06-07 07:15

See Kent's answer for practical work-around for your issue.

That said, it's a good practice to only instantiate the View once, as there is overhead associated with constructing the Visual Tree and setting up all of the bindings. Generally the View/ViewModel should be designed so that you can swap out the underlying ViewModel without the View caring or even noticing (other than DataContext changing and therefore all binding values being re-evaluated.) If you currently have logic in your Loaded event that prepares for a specific ViewModel, consider registering for notification of when DataContext changes instead (see this example).

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-06-07 07:34
<DataTemplate x:Shared="False" DataType="{x:Type VM:ResultsViewModel}">
    <VW:ResultsView/>
</DataTemplate>
查看更多
登录 后发表回答