0

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?

Dawnkeeper
  • 2,844
  • 1
  • 25
  • 41
  • Check this it seems similar question: https://stackoverflow.com/questions/15240326/treeview-hierarchicaldatatemplate-and-recursive-data – I.Step Jun 23 '21 at 07:21
  • What do you expect to see as node? – Rekshino Jun 23 '21 at 07:28
  • @I.Step I tried adapting this answer, but I end up with it failing at the highest level showing me only one TreeviewItem with the typename of the StructureItem – Dawnkeeper Jun 23 '21 at 07:32
  • @Rekshino for now only the name of each child and Io. As soon as that works I want to change formatting to highlight the difference. – Dawnkeeper Jun 23 '21 at 07:34

1 Answers1

2

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>
Rekshino
  • 6,954
  • 2
  • 19
  • 44