99 lines
2.9 KiB
C#
99 lines
2.9 KiB
C#
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;
|
|
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
|
|
|
|
namespace ComponentProgramming
|
|
{
|
|
public partial class UserTreeView : UserControl
|
|
{
|
|
private List<string> hierarchy;
|
|
|
|
public UserTreeView()
|
|
{
|
|
InitializeComponent();
|
|
hierarchy = new List<string>();
|
|
}
|
|
|
|
public void SetHierarchy(List<string> hierarchy)
|
|
{
|
|
this.hierarchy = hierarchy;
|
|
}
|
|
|
|
public void AddObjectToTree<T>(T obj)
|
|
{
|
|
TreeNode currentNode = treeView.Nodes.Count > 0 ? treeView.Nodes[0] : treeView.Nodes.Add("");
|
|
|
|
foreach (var property in hierarchy)
|
|
{
|
|
var value = obj.GetType().GetProperty(property).GetValue(obj, null).ToString();
|
|
|
|
var childNode = currentNode.Nodes.Cast<TreeNode>().FirstOrDefault(n => n.Text == value);
|
|
if (childNode == null)
|
|
{
|
|
childNode = currentNode.Nodes.Add(value);
|
|
}
|
|
|
|
currentNode = childNode;
|
|
}
|
|
}
|
|
|
|
public int SelectedNodeIndex
|
|
{
|
|
get
|
|
{
|
|
return treeView.SelectedNode?.Index ?? -1;
|
|
}
|
|
set
|
|
{
|
|
if (value >= 0 && value < treeView.Nodes.Count)
|
|
{
|
|
treeView.SelectedNode = treeView.Nodes[value];
|
|
}
|
|
}
|
|
}
|
|
|
|
public T GetSelectedObject<T>() where T : new()
|
|
{
|
|
if (treeView.SelectedNode == null)
|
|
{
|
|
throw new InvalidOperationException("Узел не выбран");
|
|
}
|
|
|
|
var node = treeView.SelectedNode;
|
|
if (node.Nodes.Count != 0)
|
|
{
|
|
throw new InvalidOperationException("Узел не конечный, сформировать объект нельзя");
|
|
}
|
|
|
|
var obj = new T();
|
|
var currentNode = node;
|
|
|
|
for (int i = hierarchy.Count - 1; i >= 0; i--)
|
|
{
|
|
var property = hierarchy[i];
|
|
var value = currentNode.Text;
|
|
var propInfo = typeof(T).GetProperty(property);
|
|
if (propInfo == null)
|
|
{
|
|
throw new InvalidOperationException($"Свойство {property} не найдено в классе {typeof(T).Name}");
|
|
}
|
|
propInfo.SetValue(obj, Convert.ChangeType(value, propInfo.PropertyType));
|
|
|
|
currentNode = currentNode.Parent;
|
|
if (currentNode == null)
|
|
{
|
|
break;
|
|
}
|
|
}
|
|
return obj;
|
|
}
|
|
}
|
|
}
|