binds an entity to TreeView control that implements the display of the tree structure as shown in. This feature is implemented through hierarchicaldatatemplate .
?
1. Business Entities
as an example, I define a well-known Folder type, which is the folder. As we all know, folders can also contain subfolders and can be nested in multiple layers. So, this is a recursive structure.
Publicclass Folder
{
PublicString Name {get; set;}
Public observablecollection<folder> Folders {get; set;}
}
2. Preparing the data
Use the following code to simulate a data read operation. The following is hard-coded data. In fact, the database can be read.
void mainpage_loaded (object sender, RoutedEventArgs e)
{
var result = new[]{
New Folder () {name="Test", Folders =new observablecollection<folder> (
New[]{
New Folder () {name="Test4"},
New Folder () {name="Test3"},
New Folder () {name="Test4", folders=new observablecollection<folder> (
New []{new Folder () {Name ="Test5"}})
}
})}};
?
Tvfolders.itemssource = result;
}
3. Binding Controls
<UserControlx:class= "Silverlighttreeviewsample.mainpage"
xmlns= "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"
Xmlns:d= "http://schemas.microsoft.com/expression/blend/2008"
XMLNS:MC= "http://schemas.openxmlformats.org/markup-compatibility/2006"
Mc:ignorable= "D"
D:designheight= "D:designwidth"= "XMLNS:SDK" ="http://schemas.microsoft.com/winfx/2006/ Xaml/presentation/sdk ">
?
<usercontrol.resources>
<sdk:hierarchicaldatatemplatex:key= "Folderitemtemplate"ItemsSource= "{Binding Folders}" >
<TextBlockText= "{Binding Name}" ></TextBlock>
</sdk:hierarchicaldatatemplate>
<StyleTargetType= "Sdk:treeviewitem" >
<SetterProperty= "isexpanded"Value= "True" ></setter>
</Style>
?
</usercontrol.resources>
?
<Gridx:name= "LayoutRoot"Background= "White" >
<sdk:treeviewName= "Tvfolders"ItemTemplate= "{StaticResource folderitemtemplate}" >
?
</sdk:treeview>
</Grid>
</UserControl>
Please note that we use a special DataTemplate : hierarchicaldatatemplate , and set it to Treeview of the ItemTemplate .
??
?
Using hierarchicaldatatemplate in Silverlight to implement a recursive tree structure for the TreeView