TreeView 데이터 바인딩(Hierarchical DataTemplate로 계층 구조 바인딩)

7647 단어 template
Hierarchical Data Template로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);
        }

    }
}
소스 코드

좋은 웹페이지 즐겨찾기