WPF日积月累之TreeView动态绑定

一、概述

本文演示了如何递归生成数据,用于绑定TreeView以及TreeItem的双击事件

二、参考代码

  1 using System;
  2 using System.Collections.Generic;
  3 using System.ComponentModel;
  4 using System.Linq;
  5 using System.Windows;
  6 using System.Windows.Controls;
  7 using System.Windows.Input;
  8 
  9 namespace BindingDemo6TreeBinding
 10 {
 11 
 12     /// <summary>
 13     /// Interaction logic for MainWindow.xaml
 14     /// </summary>
 15     public partial class MainWindow : Window
 16     {
 17         public MainWindow()
 18         {
 19             InitializeComponent();
 20 
 21             #region 用于绑定的数据
 22             List<TreeItem> grpLst = new List<TreeItem>(){
 23                 new TreeItem(){ID=0,ItemName="Root", ParentId = -1,IsExpanded=true},//设置初始状态为展开状态
 24 
 25                 new TreeItem(){ID=1,ItemName="Item1",ParentId=0},
 26                 new TreeItem(){ID=2,ItemName="Item1-1",ParentId=1},
 27                 new TreeItem(){ID=3,ItemName="Item1-2",ParentId=1},
 28                 new TreeItem(){ID=4,ItemName="Item1-3",ParentId=1},
 29 
 30                 new TreeItem(){ID=5,ItemName="Item1-3-1",ParentId=4},
 31                 new TreeItem(){ID=6,ItemName="Item1-3-2",ParentId=4},
 32 
 33 
 34 
 35                 new TreeItem(){ID=7,ItemName="Item2",ParentId=0},
 36                 new TreeItem(){ID=8,ItemName="Item2-1",ParentId=7},
 37                 new TreeItem(){ID=9,ItemName="Item2-2",ParentId=7},
 38 
 39                 new TreeItem(){ID=10,ItemName="Item3",ParentId=0}
 40             };
 41             #endregion
 42 
 43             this.cmbGoup.ItemsSource = grpLst;//comboBox数据源
 44             this.cmbGoup.SelectedValuePath = "ID";
 45             this.cmbGoup.DisplayMemberPath = "ItemName";
 46 
 47             List<TreeItem> lstGroup = getTreeData(-1, grpLst);//初始化时获取父节点为-1的数据
 48             this.tvGroup.ItemsSource = lstGroup;//数据绑定
 49         }
 50         /// <summary>
 51         /// 递归生成树形数据
 52         /// </summary>
 53         /// <param name="delst"></param>
 54         /// <returns></returns>
 55         public List<TreeItem> getTreeData(int parentid, List<TreeItem> nodes)
 56         {
 57             List<TreeItem> mainNodes = nodes.Where(x => x.ParentId == parentid).ToList<TreeItem>();
 58             List<TreeItem> otherNodes = nodes.Where(x => x.ParentId != parentid).ToList<TreeItem>();
 59             foreach (TreeItem grp in mainNodes)
 60             {
 61                 grp.ChildrenItems = getTreeData(grp.ID, otherNodes);
 62             }
 63             return mainNodes;
 64         }
 65 
 66         /// <summary>
 67         /// 下拉框关闭事件
 68         /// </summary>
 69         /// <param name="sender"></param>
 70         /// <param name="e"></param>
 71         private void cmbGoup_DropDownClosed(object sender, EventArgs e)
 72         {
 73             if (this.cmbGoup.SelectedValue == null)
 74             {
 75                 return;
 76             }
 77             int groupId = (int)this.cmbGoup.SelectedValue;//选中的组号
 78             List<TreeItem> lstGroup = getTreeData(groupId, (List<TreeItem>)cmbGoup.ItemsSource);
 79             this.tvGroup.ItemsSource = lstGroup;
 80         }
 81 
 82 
 83         private void tvDomain_MouseDoubleClick(object sender, MouseButtonEventArgs e)
 84         {
 85             TreeViewItem trvItem = sender as TreeViewItem;
 86             if(trvItem.IsSelected)
 87             {
 88                 TreeItem selectedItem = (TreeItem)(this.tvGroup.SelectedItem);
 89                 MessageBox.Show(selectedItem.ItemName);
 90             }          
 91         }
 92     }
 93     public class TreeItem:ViewModelBase
 94     {
 95         public TreeItem()
 96         {
 97             this.ChildrenItems = new List<TreeItem>();
 98             this.ParentId = 0;//主节点的父id默认为0
 99         }
100 
101         public List<TreeItem> ChildrenItems { get; set; }
102         public int ID { get; set; }//id
103         public int ParentId { get; set; }//parentID
104         public string ItemName { get; set; }
105 
106         private bool isExpanded;
107         public bool IsExpanded { get { return isExpanded; } set { isExpanded = value;
108                 OnPropertyChanged(nameof(IsExpanded));
109             } }
110 
111 
112         private bool isSelected;
113         public bool IsSelected
114         {
115             get { return isSelected; }
116             set
117             {
118                 isSelected = value;
119                 OnPropertyChanged(nameof(IsSelected));
120             }
121         }
122 
123 
124 
125 
126     }
127     public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
128     {
129         public virtual string DisplayName { get; set; }
130 
131         public event PropertyChangedEventHandler PropertyChanged;
132 
133         protected void OnPropertyChanged(string propertyName)
134         {
135             PropertyChangedEventHandler handler = PropertyChanged;
136 
137             if (handler != null)
138             {
139                 handler(this, new PropertyChangedEventArgs(propertyName));
140             }
141         }
142 
143 
144         #region IDisposable Members
145 
146         public void Dispose()
147         {
148             this.OnDispose();
149 
150         }
151 
152         protected virtual void OnDispose()
153         {
154         }
155 
156         #endregion
157     }
158 }
View Code
 1 <Window x:Class="BindingDemo6TreeBinding.MainWindow"
 2         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 3         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 4         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 5         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 6         xmlns:local="clr-namespace:BindingDemo6TreeBinding"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="350" Width="525">
 9     <Grid >
10         <Grid.RowDefinitions>
11             <RowDefinition Height="81*"/>
12             <RowDefinition Height="239*"/>
13         </Grid.RowDefinitions>
14         <Grid.ColumnDefinitions>
15             <ColumnDefinition Width="178*"/>
16             <ColumnDefinition Width="339*"/>
17         </Grid.ColumnDefinitions>
18         <StackPanel Margin="10" Grid.ColumnSpan="2">
19             <Label Content="选择组节点:"></Label>
20             <ComboBox MaxDropDownHeight="100" Name="cmbGoup" DropDownClosed="cmbGoup_DropDownClosed" ></ComboBox>
21         </StackPanel>
22         <StackPanel Margin ="10" Grid.Row="1">
23             <TreeView x:Name="tvGroup" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Visible" ScrollViewer.HorizontalScrollBarVisibility="Auto">
24                 <TreeView.ItemContainerStyle>
25                     <Style TargetType="{x:Type TreeViewItem}">
26                         <Setter Property="IsExpanded" Value="{Binding IsExpanded,Mode=TwoWay}" />
27                         <Setter Property="IsSelected" Value="{Binding IsSelected,Mode=TwoWay}"/>
28                         <EventSetter Event="MouseDoubleClick" Handler="tvDomain_MouseDoubleClick"></EventSetter>
29                     </Style>
30                 </TreeView.ItemContainerStyle>
31                 <TreeView.ItemTemplate>
32                     <HierarchicalDataTemplate ItemsSource="{Binding ChildrenItems}">
33                         <StackPanel>
34                             <TextBlock VerticalAlignment="Center" FontSize="14" Text="{Binding ItemName}" Margin="2,0,0,0"></TextBlock>
35                         </StackPanel>
36                     </HierarchicalDataTemplate>
37                 </TreeView.ItemTemplate>
38             </TreeView>
39         </StackPanel>
40         <GroupBox  Grid.Column="1" Grid.Row="1"  Margin="2" BorderThickness="0.6" BorderBrush="Silver">
41 
42 
43             <Frame x:Name="mainFrame" Margin="2" ScrollViewer.CanContentScroll="True" NavigationUIVisibility="Hidden"  />
44 
45         </GroupBox>
46     </Grid>
47 </Window>
View Code

猜你喜欢

转载自www.cnblogs.com/3xiaolonglong/p/9914634.html