Reputation: 31
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:
With a TableFields Property
SortedDictionary <Name, Field Object>
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
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