Following is the code I wrote for generating treeview hierarchy,
For Each k As KeyValuePair(Of String, GenreSet) In GenreSetDictionary
Dim t As New TreeNodeSet
t.Genre = True
t.Imagepath = k.Value.IconPath
t.Namee = k.Key
Dim pnode As New TreeViewItem
pnode.DataContext = t
pnode.Visibility = True
For Each z As DatabaseDearDataSet.DiskListRow In adpt.GetDataByGenre(t.Namee)
Dim tt As New TreeNodeSet
tt.Genre = False
tt.Imagepath = IconDictionary(z.DiskIcon).IconPath
tt.Namee = z.DiskName
Dim cnode As New TreeViewItem
cnode.DataContext = tt
pnode.Items.Add(cnode)
Next
DisksTreeView1.Items.Add(pnode)
Next
Following is the code I have used in XAML:
<TreeView Height="211" HorizontalAlignment="Left" Margin="19,15,0,0" Name="TreeView1" VerticalAlignment="Top" Width="346">
<TreeView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding ImagePath}" Width="32" Height="32"/>
<TextBlock Text="{Binding Namee}" VerticalAlignment="Center" HorizontalAlignment="Center" />
</StackPanel>
</DataTemplate>
</TreeView.ItemTemplate>
</TreeView>
However, I was not able to get that work, could you please tell me where my XAML went wrong please.
I see few minor mismatches here: the name of the
TreeViewcontrol (TreeView1 or DisksTreeView1) and theImagePathproperty (orImagepath, c# is sensible to the register of variables).But the main reason of the incorrect behavior is that the
ItemTemplateproperty is applied to theItemsSourceproperty, not to theItemsproperty.Here are two possible ways to correct the code:
1) Fixeing of the data class, item template and binding to the ItemsSource
myObservableCollectionprivate field of the typeObservableCollection(Of TreeNodeSet).DisksTreeView1.ItemsSource = myObservableCollectionDisksTreeView1.Items.Add(pnode)to the linemyObservableCollection.Add(t).Disksproperty to theTreeNodeSetclass (the type isObservableCollectiontoo)DataTemplateto the line<HierarchicalDataTemplate ItemsSource="{Binding Disks}"pnode.Items.Add(cnode)to the linet.Disks.Add(tt).2) Using the
HeaderTemplateproperty instead of theItemTemplateproperty.At first, move the DataTemplate to resources and add some key. Then add a similar code near each
TreeViewItemin the code-behind: