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
TreeView
control (TreeView1 or DisksTreeView1) and theImagePath
property (orImagepath
, c# is sensible to the register of variables).But the main reason of the incorrect behavior is that the
ItemTemplate
property is applied to theItemsSource
property, not to theItems
property.Here are two possible ways to correct the code:
1) Fixeing of the data class, item template and binding to the ItemsSource
myObservableCollection
private field of the typeObservableCollection(Of TreeNodeSet)
.DisksTreeView1.ItemsSource = myObservableCollection
DisksTreeView1.Items.Add(pnode)
to the linemyObservableCollection.Add(t)
.Disks
property to theTreeNodeSet
class (the type isObservableCollection
too)DataTemplate
to the line<HierarchicalDataTemplate ItemsSource="{Binding Disks}"
pnode.Items.Add(cnode)
to the linet.Disks.Add(tt)
.2) Using the
HeaderTemplate
property instead of theItemTemplate
property.At first, move the DataTemplate to resources and add some key. Then add a similar code near each
TreeViewItem
in the code-behind: