C# 您可以数据绑定 TreeView 控件吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/990112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can you data bind a TreeView control?
提问by TheFlash
Typically, when I use the standard TreeView control that comes with C#/VB I write my own methods to transfer data in and out of the Tree's internal hierarchy store.
通常,当我使用 C#/VB 附带的标准 TreeView 控件时,我会编写自己的方法来将数据传入和传出 Tree 的内部层次结构存储。
There might be ways to "bind" the GUI to a data store that I can point to (such as XML files), and when the user edits the tree items, it should save it back into the store. Is there any way to do this?
可能有一些方法可以将 GUI“绑定”到我可以指向的数据存储(例如 XML 文件),并且当用户编辑树项时,它应该将其保存回存储中。有没有办法做到这一点?
采纳答案by Jonathan Fingland
The following article should let you do what you want.
http://www.codeproject.com/KB/tree/bindablehierarchicaltree.aspx
下面的文章应该让你做你想做的。
http://www.codeproject.com/KB/tree/bindablehierarchicaltree.aspx
Edit:If you don't need something quite as elaborate as the above, the following might be easier/more appropriate: http://www.codeproject.com/KB/tree/dbTree.aspx
编辑:如果你不需要像上面那样复杂的东西,以下可能更容易/更合适:http: //www.codeproject.com/KB/tree/dbTree.aspx
Edit 2:Seeing as you want this to respond to changes in the treeview, you'll probably want the first option.
编辑 2:看到您希望它响应树视图中的更改,您可能需要第一个选项。
回答by Kezzla
I got around it by creating a class that Inherits TreeNode and contains an object. you can then bind a record to the node and recall it during the Click or DoubleClick event. Eg.
我通过创建一个继承 TreeNode 并包含一个对象的类来解决它。然后,您可以将记录绑定到节点并在 Click 或 DoubleClick 事件期间调用它。例如。
class TreeViewRecord:TreeNode
{
private object DataBoundObject { get; set; }
public TreeViewRecord(string value,object dataBoundObject)
{
if (dataBoundObject != null) DataBoundObject = dataBoundObject;
Text = value;
Name = value;
DataBoundObject = dataBoundObject;
}
public TreeViewRecord()
{
}
public object GetDataboundObject()
{
return DataBoundObject;
}
}
then you can bind to each node as you build your TreeView eg.
然后您可以在构建 TreeView 时绑定到每个节点,例如。
TreeView.Nodes.Add(new TreeViewRecord("Node Text", BoundObject));
//or for subNode
TreeView.Nodes[x].Nodes.Add(new TreeViewRecord("Node Text", BoundObject));
Then you can bind the DoubleClick event to something like this
然后你可以将 DoubleClick 事件绑定到这样的事情
private void TreeViewDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
object exp = ((TreeViewRecord) e.Node).GetDataboundObject();
//Do work
}