【问题标题】:WPF HierarchicalDataTemplate & ItemsControlWPF HierarchicalDataTemplate & ItemsControl
【发布时间】:2009-08-06 12:11:12
【问题描述】:

我有一个包含遵循此结构的对象的列表。这不是我正在使用的真实课程,但应该解释这个概念。

public class BaseType{}
public class TypeA : BaseType{}
public class TypeB: BaseType
{
    public List<TypeA> TypeAList { get; private set; }
}

ItemsControl 绑定的 List 是 List&lt;BaseType&gt;

XAML

<ItemsControl>
    <ItemsControl.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:TypeB}" ItemsSource = "{Binding Path=TypeAList}">
            <DataTemplate.Resources>
                <Style TargetType="TextBlock">
                    <Setter Property="FontSize" Value="18"/>
                    <Setter Property="HorizontalAlignment" Value="Center"/>
                </Style>
            </DataTemplate.Resources>
            <Grid>
                <Ellipse Fill="Gold"/>
                <StackPanel>
                    <TextBlock Margin="3,3,3,0"
         Text="{Binding Path=Description}"/>
                    <TextBlock Margin="3,0,3,7"
         Text="{Binding Path=Name}"/>
                </StackPanel>
            </Grid>
        </HierarchicalDataTemplate>
    <ItemsControl.Resources>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel></StackPanel>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

现在我希望看到的是在 TypeB 对象属性中找到的所有 TypeA 对象都将显示在 ItemsControl 中,而我只看到 TypeB 对象,它们以为 HierarchicalDataTemplate 定义的样式显示。我在 TreeView 控件中使用了相同的数据模板,它可以很好地显示子项。

  • 不能在 ItemsControl 中使用 HierarchicalDataTemplate 吗?
  • 如何在 ItemsControl 中显示父子关系?

【问题讨论】:

    标签: wpf itemscontrol hierarchicaldatatemplate


    【解决方案1】:

    您确实需要研究模板化并使用 TreeView 控件,或者构建自己的控件以使用分层数据。

    在某些情况下,您也许可以为常规项目控件设计自己的数据模板,其嵌套控件绑定到项目,例如(伪)

    <HierarchicalDataTemplate>
        <Grid DataContext="{Binding}">
            <ListBox ItemsSource="{Binding TypeAList}" />
        </Grid>
    </HierarchicalDataTemplate>
    

    上面的代码没试过

    控件需要了解 HierarchicalDataTemplate - 在上面的示例中,控件只是将其用作 DataTemplate(HierarchicalDataTemplate 派生自 DataTemplate 以简化样式和该数据模板的 DependencyProperty 类型)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多