In WPF, when is the constructor for a View object (MVVM pattern) called?
In the example application found in the followi开发者_如何学运维ng article:
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
In the CustomerView View, if you put a breakpoint in the constructor for that view, the breakpoint is hit the first time. For subsequent instances of that UserControl displayed, the constructor is not called again.
Two questions:
- What is the reason for this?
- Where can I place code I want to be executed every time a new CustomerView is created?
Only one CustomerView
is created. When you change the CustomerViewModel
, it doesn't create a new CustomerView
, it reuses the existing one.
the reason that the view is just created once, is that its in a TabControl/HeaderedContentControl .
if you use a listbox, you will see that every time a new viewmodel is added, a new view is created too.
<ListBox ItemsSource="{Binding Path=Workspaces}">
</ListBox>
instead of
<HeaderedContentControl
Content="{Binding Path=Workspaces}"
ContentTemplate="{StaticResource WorkspacesTemplate}"
Header="Workspaces"
Style="{StaticResource MainHCCStyle}"
/>
EDIT:
Where can I place code I want to be executed every time a new CustomerView is created?
if you use DataTemplates you will never create a new view by yourself. you just create a new VM/object, which then is displayed as the DataTemplate.
if you want create the views by yourself you have to go "view first" approach and then add the right ViewModel to the created view.
精彩评论