首页 > Windows开发 > 详细

WPF - MVVM 之TreeView

时间:2017-08-02 19:33:52      阅读:304      评论:0      收藏:0      [点我收藏+]

在项目中使用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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!