views:

784

answers:

1

I have a container view that looks something like this

<UserControl x:Class="Views.ContainerView">
 <UserControl.Resources>
  <ResourceDictionary>
   <DataTemplate DataType="{x:Type viewmodels:AViewModel}">
    <views:MyView />
   </DataTemplate>
   <DataTemplate DataType="{x:Type viewmodels:BViewModel}">
    <views:MyView />
   </DataTemplate>
   <DataTemplate DataType="{x:Type viewmodels:CViewModel}">
    <views:MyView />
   </DataTemplate>
   <DataTemplate DataType="{x:Type viewmodels:DViewModel}">
    <views:MyView />
   </DataTemplate>
  </ResourceDictionary>
 </UserControl.Resources>
 <Grid>
  <ListBox ItemsSource="{Binding Path=AvailableViewModels}" 
   SelectedItem="{Binding Path=CurrentViewModel}" 
   IsSynchronizedWithCurrentItem="True" />
  <ContentControl Content="{Binding Path=CurrentViewModel}" />
 </Grid>
</UserControl>

All my viewmodels inherit BaseViewModel so I turned my view into this

<UserControl x:Class="Views.ContainerView">
 <UserControl.Resources>
  <ResourceDictionary>
   <DataTemplate DataType="{x:Type viewmodels:BaseViewModel}">
    <views:MyView />
   </DataTemplate>
  </ResourceDictionary>
 </UserControl.Resources>
 <StackPanel>
  <ListBox ItemsSource="{Binding Path=AvailableViewModels}" 
   SelectedItem="{Binding Path=CurrentViewModel}" 
   IsSynchronizedWithCurrentItem="True" />
  <ContentControl Content="{Binding Path=CurrentViewModel}" />
 </StackPanel>
</UserControl>

thinking it would instantiate just a single MyView and just rebind the viewmodel when ListBox.SelectedItem changes. Am I understanding this behavior correctly? Is this a preferred practice? How can I verify that I'm not churning memory as I switch between views?

+1  A: 

It will instantiate a new MyView for each view model you use. If you want to reuse your user controls, you can set the DataContext property on each user control.

Pavel