suppose We have the interface :
public interface ITreeNode
{
string Text { get; set; }
IEnumerable<ITreeNode> Nodes { get; set; }
}
Suppose that we have the first node of a tree where every object implents that interface.
What is an easy way to display that tree ( a tree of ITreeNode ) in TreeView?
In other word, how do I adapt the entire tree of ITreeNode to System.Windows.Forms.TreeNode for System.Windows.Forms.TreeView ?
Please note : The above interface is just for getting an idea, if an alternative w开发者_StackOverflow中文版ay for adpating trees nodes of some type to TreeNodes for TreeView exist please advise.
The Windows Forms TreeView
will only ever operate on the type TreeNode
, so you will need some kind of conversion if you want to use instances of ITreeNode
with the control. I suggest an extension method, such as the one below:
public static class TreeViewExtensions {
public static void Add(this TreeNodeCollection nodes, ITreeNode node) {
TreeNode treeNode = new TreeNode(node.Text);
foreach (ITreeNode child in node.Nodes) treeNode.Nodes.Add(child);
nodes.Add(treeNode);
}
}
Then you can just add your node (and all children, and all children's children, etc) to a TreeView
control with little fuss:
myTreeView.Nodes.Add(myInstanceOfITreeNode);
With that said, there isn't a huge advantage in working with objects of a foreign interface and then converting to a TreeNode
representation - you might as well just work directly with the actual node class.
精彩评论