问题
Hallo,
I have read Easy object binding to Treeview Node,
but still have unanswered question.
if an object is associated with treenode tag property, how to access that object members/properties from that treenode ?
node1 = new TreeNode();
node1.tag = object1;
//ex:if object1 has public property valueA
//How to access valueA from node1 ??
回答1:
Maybe you can cast it back to the object1 type...
var valueA = ((object1Type)node1.tag).valueA;
回答2:
MyClass c = treeNode.Tag as MyClass;
theValue = c.TheProperty;
If you don't know the type of the object in question, then you can use System.Reflection:
System.Reflection.PropertyInfo pi = treeNode.Tag.GetType().GetProperty("SomeName");
theValue = pi.GetValue(treeNode.Tag, null);
Finally, if you want to know the names of the properties, again System.Reflection to the rescue:
System.Reflection.PropertyInfo[] pis = treeNode.Tage.GetType().GetProperties();
foreach (var pi in pis) {
theName = pi.Name;
}
来源:https://stackoverflow.com/questions/2986999/accessing-object-properties-from-a-treenode-thats-associated-with-it