码迷,mamicode.com
首页 > Windows程序 > 详细

WPF - MVVM 之TreeView

时间:2017-08-02 20:00:13      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:dev   ted   val   cte   block   enter   new t   结构   selected   

在项目中使用OnPropertyChanged方法,最简单的实例:

private event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = "")
{
PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(name));
}

private int myVar;

public int MyProperty
{
get { return myVar; }
set { myVar = value; OnPropertyChanged("MyProperty"); }
}

TreeView两层结构的实例,如下代码:

<TreeView ItemsSource="{Binding TVDataSource}" SelectedItemChanged="TreeView_SelectedItemChanged" >
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
                    <WrapPanel>
                        <TextBlock VerticalAlignment="Center" Text="{Binding Name}"/>
                    </WrapPanel>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

  TVDataSource是一个树结构集合,对象为TreeViewDataModel,其中有Name属性,Nodes集合。Nodes集合中存放TreeViewNodeDataModel对象。

这样在后台只需要给TVDataSource集合赋值,树结构就会展现出两级结构。并可以通过点击树结构进行删除等操作。

对象:

public class TreeViewDataModel
    {

        public TreeViewDataModel()
        {
            Nodes = new ObservableCollection<TreeViewNodeDataModel>();
        }
        public string Name { get; set; }

        private ObservableCollection<TreeViewNodeDataModel> nodes;
        public ObservableCollection<TreeViewNodeDataModel> Nodes
        {
            get { return nodes; }
            set { nodes = value; OnPropertyChanged("Nodes"); }
        }

        private event PropertyChangedEventHandler PropertyChanged;
        protected void OnPropertyChanged([CallerMemberName] string name = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }



        public class TreeViewNodeDataModel
        {
            public string Name { get; set; }
        }
    }

  

  

赋值:

private ObservableCollection<TreeViewDataModel> tVDataSource;
        public ObservableCollection<TreeViewDataModel> TVDataSource
        {
            get { return tVDataSource; } set {tVDataSource= value; OnPropertyChanged("TVDataSource"); } }

 

 

TVDataSource = new ObservableCollection<TreeViewDataModel>();
TreeViewDataModel tv = new TreeViewDataModel();
tv.Name = "A";
TreeViewNodeDataModel tvNode = new TreeViewNodeDataModel();
tvNode.Name = "a";
tv.Nodes.Add(tvNode);
TVDataSource.Add(tv);

 

WPF - MVVM 之TreeView

标签:dev   ted   val   cte   block   enter   new t   结构   selected   

原文地址:http://www.cnblogs.com/ouylvr0625/p/7275559.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!