Search code examples
c#wpfxamldata-bindingtreeview

How do I create a treeView for a List<List<int>?


I have a EntityDisplay class that contains 2 properties:

public sealed class EntityDisplayObject
{

    public ICollection Collection { get; private set; }

    public string CollectionName { get; private set; }

    public EntityDisplayObject(ICollection collection)
    {
        this.Collection = collection;

        this.CollectionName = $"{this.Collection.GetType().Name [{this.Collection.Count}]";
    }

}

Sometimes Collection will be a List<int>, but sometimes it will be a List<List<int>.

I currently have it working for List, but can not find a way to do it for nested lists.

This is my xaml at the moment:

<Grid x:Uid="Grid_4">

    <TreeView x:Uid="TreeView_2"
              Background="Transparent"
              BorderThickness="0"
              Padding="0">

        <TreeViewItem x:Uid="TreeViewItem_1"
                      Header="{Binding CollectionName}">

            <ListBox x:Uid="ListBox_2" MouseDoubleClick="TreeViewItem_MouseDoubleClick"
                     ItemsSource="{Binding Collection}"
                     Background="Transparent"
                     BorderThickness="0">
            </ListBox>

        </TreeViewItem>

    </TreeView>
</Grid>

Simple list working with the xaml

For nested lists, I get the tree view header and expandable option, but instead of showing me the list as the first screenshot, it gives me (Collection). Nested list currently


Solution

  • Thanks everyone for the help. At the end, this code did the job. What I had to do is for each collection, get the items and put them inside a new List property, and if any of the items are also collections, do the same to them which will give each object a List of children (if they are a collection).

    foreach (var child in collection)
    {
        if (child is ICollection childCollection && childCollection.Count > 0)
    {
        var childObject = new EntityDisplayObject(childCollection);
        this.ChildCollection.Add(childObject);
    }
    

    And this is how the xaml looks like to be able to display something like this

    Item 1
      -Item 2
        -Item 3
        -Item 4
        -Item 5
          -Item 6
      -Item 7
    
    <TreeView x:Uid="TreeView_2"
              Background="Transparent"
              BorderThickness="0"
              Padding="0"
              ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    
        <TreeViewItem x:Uid="TreeViewItem_1"
                      Header="{Binding CollectionName}">
    
            <ItemsControl ItemsSource="{Binding ChildCollection}"
                          ItemTemplateSelector="{StaticResource EntityInspectorDataTemplateSelector}"
                          Background="Transparent"
                          BorderThickness="0">
                
            </ItemsControl>
    
        </TreeViewItem>
    
    </TreeView>