TreeView 컨트롤

7181 단어 treeview
데이터 구조:
private int _id;

        private string _name;

        private int _parentId;

        private Tree _parent;

        private List<Tree> _children = new List<Tree>();



        public int Id

        {

            get { return _id; }

            set { _id = value; }

        }



        public string Name

        {

            get { return _name; }

            set { _name = value; }

        }



        public int ParentId

        {

            get { return _parentId; }

            set { _parentId = value; }

        }



        public Tree Parent

        {

            get { return _parent; }

            set { _parent = value; }

        }



        public List<Tree> Children

        {

            get { return _children; }

            set { _children = value; }

        }

xaml:
<Window.Resources>

        <HierarchicalDataTemplate x:Key="CustomTemplate" ItemsSource="{Binding Children}">

            <TextBlock Text="{Binding Name}" />

        </HierarchicalDataTemplate>

    </Window.Resources>    

    <Grid>

        <TreeView Height="200" HorizontalAlignment="Left" Margin="10,10,0,0" Name="treeView1" VerticalAlignment="Top" Width="120" ItemTemplate="{StaticResource CustomTemplate}" />

    </Grid>

cs:
private void SecondPage_Loaded(object sender, RoutedEventArgs e)

        {

            treeView1.ItemsSource = InitTreeView();

        }

        private List<Tree> InitTreeView()

        {

            List<Tree> rootList = new List<Tree>();

            var list = _dbModel.Tree.ToList();

            foreach (var i1 in list)

            {

                if (i1.ParentID == 0)

                    rootList.Add(i1);

                else

                {

                    foreach (var i2 in list)

                    {

                        if (i2.ID == i1.ParentID)

                        {

                            i1.Parent = i2;

                            i2.Children.Add(i1);

                        }

                    }

                }

            }

            return rootList;

        }

좋은 웹페이지 즐겨찾기