易对象绑定到TreeView节点 [英] Easy object binding to Treeview Node

查看:80
本文介绍了易对象绑定到TreeView节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎样才能对象绑定到C#中的树视图(的WinForms)节点

How can I bind an object to a treeview (Winforms) node in C#?

我想到的是这样ExNode:Windows.Forms.Node可以采取对象除了树节点名成员......但我不知道这是正确的做法。

I thought of something like ExNode : Windows.Forms.Node that can take an object as member besides the treenode name... however I am not sure that is the right approach.

推荐答案

恕我直言,你有几个策略:

imho you have several strategies :


  1. 坚持任何类型的任何节点的Tag属性的对象:缺点:你必须投它回到它的原生形态当您检索它使用它:如果原始形式是什么,但类型对象

  1. stick an object of any type in the Tag property of any Node : downside : you'll have to cast it back to its 'native form' when you retrieve it to use it : if that "native form" is anything but type 'Object.

子类树节点,并添加一个公共领域,公共属性,或什么的,你的对象......甚至列表......或任何你需要与节点关联。

sub-class TreeNode, and add a public fields, Public Properties, or whatever, for your objects ... or even List ... ... or whatever you need to associate with the Node.

假设你的对象是同一类型的,你可以创建类型的词典:字典<树节点,myObjectType>中实例化,并根据需要,存储树节点及其关联的对象(s)表示,方式一键/值对。

assuming your objects are of the same type, you could create a dictionary of type : Dictionary <TreeNode, myObjectType>, instantiate it, and, as needed, store a TreeNode and its associated Object(s) that way as a Key/Value Pair.

策略#1,#3有你可以存储的优势只在需要策略#2相关联的对象:更适合在那里你预见所有树节点都将有一个相关联的对象(S)的情况下

Strategies #1, and #3 have the advantage that you can store an associated object ONLY as needed Strategy #2 : is more suited to the case where you anticipate every TreeNode is going to have an associated object(s).

当然与stragies #1和#3,则需要在运行时对与特定节点相关联的物体的存在或不存在来测试

Of course with stragies #1 and #3, you will need to test at run-time for the presence or absence of an object associated with a particular Node.

策略#1是一个简单的测试:如果节点的标签欢迎使用属性为Null:你知道有没有对象:如果不为空......而且可能有不止一种类型存储在标签领域的对象......那么你就必须拔出Tag对象,并确保它是正确的类型为:(下面的示例假设一个公共类,1级,已经被分配给在TreeView的第一个节点的标记:

Strategy #1's an easy test : if the Tag propety of the Node is Null : you know there's no object : if not null ... and there may be more than one type of object stored in the Tag field ... then you'll have to pull out the Tag object, and make sure it's the right type as in : (the example that follows assumes a public class, "Class1," has been assigned to tag of the first node in the TreeView :

TreeNode thisNode = theTreeView.Nodes[0];
if (((thisNode.Tag != null) && (thisNode.Tag is Class1))) ... handle the object ...

战略#3是更容易一些,因为你可以评估,如果字典<节点,myObject的方式>。载节点作为关键

Strategy #3 is a little easier since you can just evaluate if the Dictionary<Node, myObject>.Contains the Node as a Key.

这篇关于易对象绑定到TreeView节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆