COP_Petrushin_PIbd-32/Library14Petrushin/HierarchicalTreeView.cs
2024-09-17 12:40:52 +04:00

97 lines
2.9 KiB
C#

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<string> hierarchy;
private Dictionary<string, bool> alwaysNewBranch;
public HierarchicalTreeView()
{
InitializeComponent();
hierarchy = new List<string>();
alwaysNewBranch = new Dictionary<string, bool>();
}
public void SetHierarchy(List<string> hierarchy, Dictionary<string, bool> alwaysNewBranch)
{
this.hierarchy = hierarchy;
this.alwaysNewBranch = alwaysNewBranch;
}
public void AddObjectToTree<T>(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<TreeNode>().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<T>() 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;
}
}
}