using Library14Petrushin.Classes; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Library14Petrushin { public partial class HierarchicalTreeView : UserControl { private List hierarchy; private Dictionary alwaysNewBranch; public HierarchicalTreeView() { InitializeComponent(); hierarchy = new List(); alwaysNewBranch = new Dictionary(); } public void SetHierarchy(List hierarchy, Dictionary alwaysNewBranch) { this.hierarchy = hierarchy; this.alwaysNewBranch = alwaysNewBranch; } public void AddObjectToTree(T obj, string stopAtProperty) { TreeNode currentNode = treeView1.Nodes.Count > 0 ? treeView1.Nodes[0] : treeView1.Nodes.Add(""); foreach (var property in hierarchy) { var value = obj.GetType().GetProperty(property).GetValue(obj, null).ToString(); bool createNewBranch = alwaysNewBranch.ContainsKey(property) && alwaysNewBranch[property]; var childNode = currentNode.Nodes.Cast().FirstOrDefault(n => n.Text == value); if (childNode == null || createNewBranch) { childNode = currentNode.Nodes.Add(value); } currentNode = childNode; if (property == stopAtProperty) { break; } } } public int SelectedNodeIndex { get { return treeView1.SelectedNode?.Index ?? -1; } set { if (value >= 0 && value < treeView1.Nodes.Count) { treeView1.SelectedNode = treeView1.Nodes[value]; } } } public T GetSelectedObject() where T : new() { if (treeView1.SelectedNode == null) { throw new InvalidOperationException("Узел не выбран"); } var node = treeView1.SelectedNode; if (node.Nodes.Count != 0) { throw new InvalidOperationException("Узел не конечный, сформировать класс нельзя"); } var obj = new T(); foreach (var property in hierarchy) { var value = node.Text; obj.GetType().GetProperty(property).SetValue(obj, value); node = node.Parent; if (node == null) { break; } } return obj; } } }