Creating TreeViewItem children using ItemSource from List<string>

71 views Asked by At

I am trying to bind a list of strings into a TreeViewItem but for some reason no data is being shown, nor any errors.

In the XAML I have the following in my TreeViewItem.

<TreeView Name="treeContainer">
            <TreeViewItem Header="Tables" Name="treeTablesContainer">
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="{x:Type TreeViewItem}" />
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <HierarchicalDataTemplate
                        DataType="{x:Type system:String}">
                        <TextBlock Text="{Binding dbTables}" />
                    </HierarchicalDataTemplate>
                </ItemsControl.ItemTemplate>
            </TreeViewItem>
        </TreeView>

In the cs code I have the following:

dbTables = new List<string>();
            dbTables.Add("Tabl2");
            treeTablesContainer.ItemsSource = dbTables;

The TreeViewItem can be expanded and collapsed, however, there are no children bein shown and I can't see how to get this to work.

I've done something similar to this in another part of the project, except the different the List is of type my own class with properties which I can reference in the line <TextBlock Text="{Binding dbTables}" /> but I think this isn't working because of the List<string> type so I have no property to access, is my thinking correct and if so, how can I fix this.

2

There are 2 answers

1
Firoz On BEST ANSWER

Hierarchical data template is data template for each item in out data source. That mean in your example binding of text block searching dbTables on string class. your xaml code should look like

 <TreeView Name="treeContainer">
        <TreeViewItem Header="Tables" Name="treeTablesContainer">
            <ItemsControl.ItemContainerStyle>
                <Style TargetType="{x:Type TreeViewItem}" />
            </ItemsControl.ItemContainerStyle>
            <ItemsControl.ItemTemplate>
                <HierarchicalDataTemplate>
                    <TextBlock Text="{Binding}" />
                </HierarchicalDataTemplate>
            </ItemsControl.ItemTemplate>
        </TreeViewItem>
    </TreeView>
0
Dark Knight On
<TreeView Name="treeContainer">
            <TreeViewItem Header="Tables" Name="treeTablesContainer">
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="{x:Type TreeViewItem}" />
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <HierarchicalDataTemplate>
                        <TextBlock Text="{Binding }" />
                    </HierarchicalDataTemplate>
                </ItemsControl.ItemTemplate>
            </TreeViewItem>
        </TreeView>

Just remove dbTables in binding as its not binding to any property named dbTables in your collection