K.G
K.G

Reputation: 31

WPF TreeView data binding to custom objects

I am having trouble understanding how to Bind Data to a WPF TreeView when custom objects are used. I have researched and watched tutorials but I am still stuck.

BACKGROUND: consider three classes (I have simplified my problem to this). They represent a database which has a Table, each table can have Fields. There are a list of Tables.

1) TableList Class With Property

List<Table Objects> 

2) Table Class:

3) Field Class:

An example of my current attempt to bind a field (lowest level) to Table.TableFields.Key

<DataTemplate x:Key="fieldTemplate">
            <TextBlock Text="{Binding Path=Table.TableFields.Key}"/>
</DataTemplate>

DESIRED OUTPUT - a hierarchical view of the table list, containing tables and their fields.

Table 1
   Field 1
   Field 2
   Field 3
Table 2
   Field 1
   Field 2
   Field 3
 Table N
   Field N

I am confused with how to bind custom objects and access the information like this.

Upvotes: 0

Views: 3869

Answers (1)

Nitin Purohit
Nitin Purohit

Reputation: 18580

This will display your TreeView

      <TreeView ItemsSource="{Binding TableList}">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource = "{Binding Path=TableFields}">
                    <TextBlock Text="{Binding Path=Name}"/>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=Key}"/>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

Upvotes: 1

Related Questions