wpf中TreeView双击事件中获取当前节点、父节点以及子节点
作者:互联网
由于工作中需要,第一次研究wpf,所以简单记录下
wpf:界面内容
<TreeView x:Name="TvDepartment" Background="Gray" DockPanel.Dock="Bottom" MouseDoubleClick="TvDepartment_MouseDoubleClick">
</TreeView>
wpf:绑定数据供参考
List<Department> roots = new List<Department>(); foreach (Department department in departments) { if (departments.Count(d => d.DepartID == department.ParentDepartID) == 0) { roots.Add(department); } } TreeViewItem rootN = new TreeViewItem(); rootN.Header = "部门信息"; rootN.Tag = 0; TvDepartment.Items.Add(rootN); foreach (var root in roots) { TreeViewItem rootNode = new TreeViewItem(); rootNode.Header = root.DepartName; rootNode.Tag = root; GetChildren(rootNode, root); rootN.Items.Add(rootNode); }
private void GetChildren( TreeViewItem node, Department department) { IEnumerable<Department> children = departments.Where(d => d.ParentDepartID == department.DepartID); foreach (Department dep in children) { TreeViewItem childNode = new TreeViewItem(); childNode.Header = dep.DepartName; childNode.Tag = dep; GetChildren(childNode, dep); node.Items.Add(childNode); } }
wpf:获取节点的数据
private void TvDepartment_MouseDoubleClick(object sender, MouseButtonEventArgs e) { //获取当前选中的节点 var curSelect = this.TvDepartment.SelectedItem as TreeViewItem; if (curSelect != null) { //获取当前选中节点的父节点 DependencyObject curSParent = curSelect.Parent; if (curSParent.GetType().Name == "TreeView") //表示:顶节点 { var curSelectParent = curSParent as TreeView; Department departP = (Department)curSelectParent.Tag; } else if (curSParent.GetType().Name == "TreeViewItem")//表示:除了顶节点的其它节点 { var curSelectParent = curSParent as TreeViewItem; Department departP = (Department)curSelectParent.Tag; } deptIds.Clear(); if (curSelect.Tag.ToString() != "0") { Department depart = (Department)curSelect.Tag; deptIds.Add(depart.DepartID); //获取当前选中节点的子节点 if (curSelect.Items.Count > 0) { foreach (var item in curSelect.Items) { var curSelectSub = item as TreeViewItem; Department departSub = (Department)curSelectSub.Tag; deptIds.Add(departSub.DepartID); } } } ShowData(false); } }
标签:curSelect,节点,双击,Add,Tag,Department,wpf,TreeViewItem 来源: https://www.cnblogs.com/ggll611928/p/16207247.html