Following is the code I wrote for g开发者_JAVA技巧enerating 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 the ImagePath
property (or Imagepath
, c# is sensible to the register of variables).
But the main reason of the incorrect behavior is that the ItemTemplate
property is applied to the ItemsSource
property, not to the Items
property.
Here are two possible ways to correct the code:
1) Fixeing of the data class, item template and binding to the ItemsSource
- Create the
myObservableCollection
private field of the typeObservableCollection(Of TreeNodeSet)
. - Add to the constructor the line
DisksTreeView1.ItemsSource = myObservableCollection
- Change the line
DisksTreeView1.Items.Add(pnode)
to the linemyObservableCollection.Add(t)
. - Add the
Disks
property to theTreeNodeSet
class (the type isObservableCollection
too) - In the xaml replace the line with
DataTemplate
to the line<HierarchicalDataTemplate ItemsSource="{Binding Disks}"
- Change the line
pnode.Items.Add(cnode)
to the linet.Disks.Add(tt)
.
2) Using the HeaderTemplate
property instead of the ItemTemplate
property.
At first, move the DataTemplate to resources and add some key. Then add a similar code near each TreeViewItem
in the code-behind:
Dim pnode As New TreeViewItem
pnode.DataContext = t
pnode.Header = t
pnode.HeaderTemplate = Resources("someKey")
精彩评论