WPF根据绑定对象的Class绘制UserControl

WPF Draw UserControl based on the Class of the bound object

我正在开发一个可以显示项目的菜单。

因此我有一个 UserControl 'MenuItem',它显示 'MenuItemEntity' 类型的实体。 因为有以不同方式显示的子菜单,还有另一个 UserControl 'MenuItemGroup',它绑定到包含不同 MenuItemEntities 的类型 'MenuItemGroupEntity' 的实体。

现在我有以下问题: 'menu' 应该绑定到 'MenuEntity' 类型的实体。 在这里面我想要一个 ObservableCollection,它包含 MenuItemEntity 和 MenuItemGroupEntity,它们使用 ItemsControl 显示在 StackPanel 中。 但我不知道是否有任何方法可以分析绑定集合中的实际元素以绘制 MenuItem 或 MenuItemGroup。也许是开关之类的东西?

通常我会像这样在 'MenuEntity' 中绑定 ObservableCollection 的项目:

<ItemsControl ItemsSource="{Binding MenuItemAndGroupCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>

            <!-- IS THERE ANY WAY TO SWITCH BASED ON THE CLASS TYPE? -->
            <local:MenuItemGroup DataContext="{Binding}" />
            <local:MenuItem DataContext="{Binding}" />
            <!-- IS THERE ANY WAY TO SWITCH BASED ON THE CLASS TYPE? -->

        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

我希望有人能帮我解决这个问题=(

只需使用 "implicit" DataTemplates,像这样:

<Window>
  <Window.Resources>
      <DataTemplate DataType="{x:Type local:MyClass1}">
           <local:MyUserControl1/>
      </DataTemplate>

      <DataTemplate DataType="{x:Type local:MyClass2}">
           <local:MyUserControl2/>
      </DataTemplate>

      <!-- and so on... -->
  </Window.Resources>

  <ItemsControl ItemsSource="{Binding MenuItemAndGroupCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Vertical"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <!-- Do NOT specify an ItemTemplate here -->
  </ItemsControl>
</Window>