用HierarchicalDataTemplate做了个treeView的数据绑定,好处是不管有多少层,自动绑定哈,省事多了。
关键代码:
<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);
}
}
}
附:源代码
 
                    
                 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号