【问题标题】:WPF Draw UserControl based on the Class of the bound objectWPF根据绑定对象的Class绘制UserControl
【发布时间】:2015-10-20 13:09:47
【问题描述】:

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

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

现在我有以下问题: “菜单”应绑定到“菜单实体”类型的实体。 在这里面我想要一个 ObservableCollection,它包含 MenuItemEntity 的 AND 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>

希望有人能帮帮我=(

【问题讨论】:

    标签: c# wpf data-binding types user-controls


    【解决方案1】:

    简单地使用“隐式”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>
    

    【讨论】:

    • 这就是我要找的。非常感谢你。这比我想象的要容易得多。
    猜你喜欢
    • 2019-05-08
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多