我正在开发 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(2, "NetworkControl.AddressData.MessageOriginatorID.Value"));
messageElements.Add(new MessageElement(3, "VehicleSummary.VehicleIdentification.IdentificationID.Value"));
messageElements.Add(new MessageElement(3, "TitleSummary.JurisdictionTitlingKeyText.Value"));
messageElements.Add(new MessageElement(1, "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"
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>())
}
);
}
}
我怎样才能删除这个异常,以便我可以递归地构建我的树?