WPF HierarchicalDataTemplate & ItemsControl

徘徊边缘 提交于 2020-01-06 16:54:28

问题


I have a list containing objects that follow this structure. This is not the real classes I am working with, but should explain the concept.

CLASSES

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

The List that the ItemsControl binds to is a List<BaseType>

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>

Now what I would expect to see is all the TypeA objects found in the TypeB object property to be displayed in the ItemsControl, instead I only see the TypeB objects, displayed with the styles defined for the HierarchicalDataTemplate. i've used the same datatemplate in a TreeView control, where it displays the child items fine.

  • Can you not use a HierarchicalDataTemplate in an ItemsControl?
  • How do you go about displaying a parent child relationship in an ItemsControl?

回答1:


You really need to look into templating and working with the TreeView control, or build your own control to work with the hierarchical data.

In some situations, you may be able to design your own data template for a regular items control whose nested controls bind to the item, such as (psuedo)

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

Haven't tried the code above

The control needs to be aware of the HierarchicalDataTemplate - and in the example above, the control is simply using it as a DataTemplate (HierarchicalDataTemplate derives from DataTemplate for simplicity in styles and the DependencyProperty's type for that data template).



来源:https://stackoverflow.com/questions/1222008/wpf-hierarchicaldatatemplate-itemscontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!