我正在开发 WPF 项目以在TreeView
. 我有 propertyPaths(例如:NetworkControl.AlternateIndexText.Value")路径有 id。
树模型
public class MessageElement
{
private int id;
public string Name { get; set; }
public string path { get; set; }
public List<MessageElement> Children { get; set; }
public List<MessageElement> messageElements { get; set; }
public MessageElement()
{
Children = new List<MessageElement>();
messageElements = new List<MessageElement>();
}
public MessageElement(int id, string name, List<MessageElement> children)
{
this.ID = id;
this.Name = name;
this.Children = children;
}
public MessageElement(int id, string path)
{
this.ID = id;
this.path = path;
}
}
起订量一些数据
public List<MessageElement> GetRequestTreeNodes()
{
messageElements.Add(new MessageElement(1, "NetworkControl.AlternateIndexText.Value"));
messageElements.Add(new MessageElement(2, "NetworkControl.AddressData.DestinationID"));
messageElements.Add(new MessageElement(3, "NetworkControl.AddressData.MessageOriginatorID.Value"));
messageElements.Add(new MessageElement(4, "VehicleSummary.VehicleIdentification.IdentificationID.Value"));
messageElements.Add(new MessageElement(4, "TitleSummary.JurisdictionTitlingKeyText.Value"));
messageElements.Add(new MessageElement(6, "VehicleSummary.VehicleIdentification.IdentificationID.Value"));
return messageElements;
}
递归创建树:
public List<MessageElement> BuildTree(IEnumerable<MessageElement> messageElements)
{
return (
from element in messageElements // Ex:(1, "NetworkControl.AlternateIndexText.Value")
let elementId = element.id // get id from message element
let splitPath = element.path.Split('.') // get path from message element
group element by element.path.Split('.')[0] into pathElementGroup
select new MessageElement(ID, path)
{
ID = elementId, ?? // id of each path Ex: 1 => "NetworkControl.AlternateIndexText.Value"
// this is the hardest part I have to reserve each ID that belongs to the path
//Like I showed in the example
Name = pathElementGroup.Key, //name of each tree node to be displayed on tree
Children = BuildTree( //create child from the propertyPath
(from propertyPathElement in pathElementGroup
where propertyPathElement.path.Length > pathElementGroup.Key.Length + 1
select new MessageElement())
.ToList<MessageElement>())
}
);
}
}
如何为用于构建树节点的每个属性路径保留每个 ID。