一种方式是创建一个派生TreeNode对象,迫使它包含List<data>
:
// requires declaration of : using System.Windows.Forms;
// sample data class
public class data
{
public string Name;
public int ID;
}
public class XTreeNode : TreeNode
{
List<data> theData = new List<data>();
public XTreeNode(string theNodeID)
{
this.Text = theNodeID;
}
public void addData(data newData)
{
theData.Add(newData);
}
}
这里是建筑的一个实例的(不优雅)样本上述数据结构可能看起来像(上一个WinForm):假设你有一个TreeView,名为“为TreeView1的形式:
XTreeNode currentNode;
data currentData;
for (int i = 0; i < 10; i++)
{
// create the node and add it to the 'treeView1
currentNode = new XTreeNode(i.ToString());
treeView1.Nodes.Add(currentNode);
// add some data entries to the List<data> of the derived TreeNode
currentData = new data {Name = "one", ID = 100};
currentNode.addData(currentData);
currentData = new data { Name = "two", ID = 200 };
currentNode.addData(currentData);
currentData = new data { Name = "three", ID = 300 };
currentNode.addData(currentData);
// sample of adding a child node
currentNode.Nodes.Add(new XTreeNode((i * 100).ToString()));
}
有关的问题,如何哟您将直观地显示与每个节点关联的List<data>
:通常的方法是将Treeview与ListView组合起来,并同步它们的位置和项目高度:然后在与相应的TreeNode相同的“行”上显示List<data>
。
当然,您可以实现您自己的Node和NodeCollection实体,这些实体完全独立于任何控件:此示例展示了一个依赖.NET控件的混合大小写来充当数据结构和呈现机制。
在CodeProject上有一个很好的组合TreeView/ListView的例子,多年来一直保持,更新和扩展:Phillip Piper's:"A Much Easier to Use ListView",2006年首次发布,2009年10月最后更新:它的功能非常丰富,如果与商业组件相比,毫不逊色。
这里的一个关键问题可能是:你是否在寻找一个在代码中定义“纯数据结构”的答案:独立于任何现有的WinForms控件或第3个。党的控制。或者,你是否愿意接受使用现有或第三方案的答案。党控制?同样,请参阅我对Lokey的回答的评论。 – BillW 2010-03-04 14:36:26