当您在 Resources 部分中声明 DataTemplate 时,您可以选择...您可以为其提供一个名称,然后使用该名称来引用它,或者您不指定名称。如果DataTemplate 没有名称(或x:Key 值),那么它将自动应用于其中指定类型的所有对象,除非它们有另一个DataTemplate 显式设置并命名为DataTemplate。
因此,您可以将以下内容添加到您的应用程序Resources 部分(在App.xaml 中),它将应用于您应用程序中的所有视图模型:
<DataTemplate DataType="{x:Type ViewModels:CircleVM}">
<Views:Circle />
</DataTemplate>
<DataTemplate DataType="{x:Type ViewModels:RectangleVM}">
<Views:Rectangle />
</DataTemplate>
请注意,您将需要添加所需的 XML 命名空间...如下所示:
xmlns:ViewModels="clr-namespace:YourApplicationName.FolderNameIfApplicable"
xmlns:Views="clr-namespace:YourApplicationName.FolderNameIfApplicable"
现在,每当您将 CircleVM 类的实例添加到 UI 中时,都会显示相关的 Circle.xaml 文件:
<ContentControl Content="{Binding YourViewModelProperty}" />
要在两个视图模型之间切换,请创建一个如上的属性...同样,您有两个选择:
public object YourViewModelProperty // with valid getter/setter removed here
或者更好的是,创建一个实现 INotifyPropertyChangedinterface 的 BaseViewModel 类并从中扩展您的所有视图模型:
public BaseViewModel YourViewModelProperty // with valid getter/setter removed here
当用户改变他们的选择时要采取的最后一步是设置这个属性的值:
if (userHasChosenCircle) YourViewModelProperty = new CircleVM();
else YourViewModelProperty = new RectangleVM();