104 lines
3.2 KiB
C#
104 lines
3.2 KiB
C#
using System.Xml;
|
|
|
|
namespace COP
|
|
{
|
|
public partial class UserTreeView : UserControl
|
|
{
|
|
private event Action? _errorOccured;
|
|
public List<string> Hierarchy;
|
|
public string Error { get; private set; }
|
|
public UserTreeView()
|
|
{
|
|
InitializeComponent();
|
|
Error = string.Empty;
|
|
Hierarchy = new();
|
|
}
|
|
// иерархия
|
|
// метод заполнения иерархии
|
|
|
|
|
|
public event Action AnErrorOccurred
|
|
{
|
|
add { _errorOccured += value; }
|
|
remove { _errorOccured -= value; }
|
|
}
|
|
|
|
public int SelectedItemIndex
|
|
{
|
|
get
|
|
{
|
|
if (treeView.SelectedNode == null)
|
|
{
|
|
return -1;
|
|
}
|
|
return treeView.SelectedNode.Index;
|
|
}
|
|
}
|
|
|
|
public T? GetSelectedObject<T>() where T : class, new()
|
|
{
|
|
// параметризованный
|
|
//проверка есть или нет иерархии
|
|
TreeNode selectedNode = treeView.SelectedNode;
|
|
if (Hierarchy == null)
|
|
{
|
|
throw new Exception("Hierarchy is not set.");
|
|
}
|
|
if (selectedNode?.FirstNode != null)
|
|
{
|
|
throw new Exception("Not a last level node.");
|
|
}
|
|
T currentBranch = new T();
|
|
Hierarchy.Reverse();
|
|
foreach (var property in Hierarchy)
|
|
{
|
|
typeof(T).GetProperty(property).SetValue(currentBranch, Convert.ChangeType(selectedNode.Text, typeof(T).GetProperty(property).PropertyType));
|
|
|
|
selectedNode = selectedNode.Parent;
|
|
}
|
|
Hierarchy.Reverse();
|
|
return currentBranch;
|
|
|
|
}
|
|
//проверка что выбранный элем последний в ветке
|
|
|
|
public void PopulateTree<T>(List<T> items)
|
|
{
|
|
treeView.BeginUpdate();
|
|
treeView.Nodes.Clear();
|
|
if (items == null)
|
|
{
|
|
throw new ArgumentNullException(nameof(items));
|
|
}
|
|
if (Hierarchy == null)
|
|
{
|
|
throw new Exception("Hierarchy is not set.");
|
|
}
|
|
|
|
foreach (var item in items)
|
|
{
|
|
TreeNodeCollection treeViewNodes = treeView.Nodes;
|
|
foreach (var elem in Hierarchy)
|
|
{
|
|
bool flag = false;
|
|
for (int i = 0; i < treeViewNodes.Count; i++)
|
|
{
|
|
if (item.GetType().GetProperty(elem).GetValue(item).ToString() == treeViewNodes[i].Text)
|
|
{
|
|
treeViewNodes = treeViewNodes[i].Nodes;
|
|
flag = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!flag)
|
|
{
|
|
var newNode = treeViewNodes.Add(item.GetType().GetProperty(elem).GetValue(item).ToString());
|
|
treeViewNodes = newNode.Nodes;
|
|
}
|
|
}
|
|
}
|
|
treeView.EndUpdate();
|
|
}
|
|
}
|
|
}
|