我有一个容器视图,大致长这样:
所有的视图模型都继承自BaseViewModel,因此我将我的视图转换为以下格式:
<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>
所有的视图模型都继承自BaseViewModel,因此我将我的视图转换为以下格式:
<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>
我认为它只会实例化一个MyView,并在ListBox.SelectedItem更改时重新绑定视图模型。我理解这种行为正确吗?这是一种首选做法吗?我如何验证在切换视图时没有浪费内存?