Recursive Treeview with multiple classes

the setup

I have a ViewModel with an ObservableCollection<StructureItem> and a View to display it. The class itself is recursive:

public class StructureItem
{
        public List<StructureItem> Children { get; set; } = new List<StructureItem>();

        public List<IoItem> Ios { get; set; } = new List<IoItem>();

        public string Name { get; set; }
}

and here is the IoItem

public class IoItem
{
    public string Name { get; set; }

    public int Position { get; set; }
}

The current xaml for the TreeView

<TreeView ItemsSource = "{Binding Structure}">
            <TreeView.Resources>
                <DataTemplate DataType="kernel:IoItem">
                    <Label Content="{Binding Name}"></Label>
                </DataTemplate>
            </TreeView.Resources>
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="kernel:StructureItem">
                    <Label Content="{Binding Name}"></Label>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
</TreeView>

the problem

I have tried multiple different xaml, but the best result I get is that the StructureItem are displayed correctly (see above). The IoItem is either ignored or it breaks the whole Treeview.

How to display this structure using xaml?

1 answer

  • answered 2021-06-23 07:57 Rekshino

    If you want to to see the names of IoItem, then just add them to the ItemTemplate as e.g. ListBox:

    <TreeView ItemsSource = "{Binding Structure}">
        <TreeView.Resources>
            <DataTemplate DataType="{x:Type kernel:IoItem}">
                <Label Content="{Binding Name}"></Label>
            </DataTemplate>
        </TreeView.Resources>
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="kernel:StructureItem">
                <StackPanel>
                    <Label Content="{Binding Name}"></Label>
                    <ListBox ItemsSource="{Binding Ios}"/>
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>