HierarchicalDataTemplate is used to bind treeView data. The advantage is that no matter how many layers there are, it is easier to bind them automatically.
Key code:
<UserControl.Resources>
<Common:HierarchicalDataTemplate x:Key="TreeNode" ItemsSource="{Binding Path=TreeNodes}">
<TextBlock FontWeight="Bold" Text="{Binding Path=Text}" MouseLeftButtonUp="TextBlock_MouseLeftButtonUp"/>
</Common:HierarchicalDataTemplate>
</UserControl.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<sdk:TreeView x:Name="tree123" ItemsSource="{Binding Path=TreeNodes}" ItemTemplate="{StaticResource TreeNode}">
</sdk:TreeView>
</Grid>
Namespace Tree
{
Public partial class MainPage: UserControl
{
Public MainPage ()
{
InitializeComponent ();
Tree tree = new Tree ();
Tree. TreeNodes = new List <TreeNode> ();
For (int I = 0; I <5; I ++)
{
TreeNode child = new TreeNode ();
Child. Id = I;
Child. Text = "root" + I. ToString ();
Child. TreeNodes = new List <TreeNode> ();
For (int j = 0; j <I; j ++)
{
TreeNode sub = new TreeNode ();
Sub. Id = j;
Sub. Text = "sub" + j. ToString ();
Sub. TreeNodes = new List <TreeNode> ();
Child. TreeNodes. Add (sub );
For (int x = 0; x <50; x ++)
{
TreeNode subSub = new TreeNode ();
SubSub. Id = x;
SubSub. Text = "subSub" + x. ToString ();
Sub. TreeNodes. Add (subSub );
}
}
Tree. TreeNodes. Add (child );
} Tree123.DataContext = tree;
}
Private void TextBlock_MouseLeftButtonUp (object sender, MouseButtonEventArgs e)
{
TreeNode treenode = this. tree123.SelectedItem as TreeNode;
MessageBox. Show (treenode. Text );
}
}
}
Appendix: source code