首页 > 代码库 > WPF - MVVM 之TreeView

WPF - MVVM 之TreeView

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