문제

In a .NET treeview you can create nodes, subnodes and elements. All I seem to be able to do is give them names.

But how can I attach information (any object) to an element?

도움이 되었습니까?

해결책

Use the Tag property of the TreeNode to attach an arbitrary object to it.

This doesn't affect the TreeView in any way. It is especially useful in your event handlers, (e.g. AfterSelect) because allows you to refer back to one of "your" objects from the TreeNode that is referenced.

Remember that Tag is of type Object, so you'll want to be careful how you access it. Here's some sample code to show how (I feel) it is best used:

public Form1()
{
    InitializeComponent();
    theTree.AfterSelect += (sender, args) => ShowSelectedNode();
}

private void ShowSelectedNode() {
    var node = theTree.SelectedNode;

    var viewable = node.Tag as IViewable;
    if (viewable != null) {
        viewable.View(this);
    }
}

Note that this is the correct use of the as operator.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top