【问题标题】:Assign different images for different nodes in TreeView为 TreeView 中的不同节点分配不同的图像
【发布时间】:2012-06-18 08:21:29
【问题描述】:

在我的树形视图中,我可以加载带有图像的 xml 数据,但此代码将公共图像应用于所有节点。

如何为Parent node, sub_child node..etc 应用特定图像。例如,我想根据 XML 结构为 countries, country, name, states, state 分配不同的图像。

我在图像目录中加载了 5 个不同的图像。我需要一些示例来向我的树视图添加不同的图像。

private void populateTree()
{
    ImageList li = new ImageList();
    li.ImageSize = new Size(32, 32);
    li.ColorDepth = ColorDepth.Depth32Bit;
    treeView1.ImageList = li;

    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Application.StartupPath + @"\images");
    foreach (System.IO.FileInfo file in dir.GetFiles("*.*"))
    {
        li.Images.Add(file.Name, Image.FromFile(@"images\" + file.Name));
        treeView1.Nodes.Add(null, file.Name, file.Name.ToString(), file.Name.ToString());
    }

    //treeView1.ImageList = li;

    //treeView1.SelectedNode.ImageIndex = 0;
    //treeView1.SelectedNode.SelectedImageIndex = 1;

    var filename = @"C:\Countries.xml";
    //First, we'll load the Xml document
    XmlDocument xDoc = new XmlDocument();
    xDoc.Load(filename);

    //Now, clear out the treeview, and add the first (root) node
    treeView1.Nodes.Clear();
    treeView1.Nodes.Add(new TreeNode(xDoc.DocumentElement.Name));
    TreeNode tNode = new TreeNode();
    tNode = (TreeNode)treeView1.Nodes[0];
    //Here make a call to AddNode, where we'll add all of our nodes
    addTreeNode(xDoc.DocumentElement, tNode);

    //Expand the treeview to show all nodes
    treeView1.ExpandAll();



}


private void addTreeNode(XmlNode xmlNode, TreeNode treeNode)
{
    XmlNode xNode;
    TreeNode tNode;
    XmlNodeList xNodeList;

    if (xmlNode.HasChildNodes) //The current node has children
    {
        xNodeList = xmlNode.ChildNodes;

        for (int x = 0; x <= xNodeList.Count - 1; x++) //Loop through the child nodes
        {
            xNode = xmlNode.ChildNodes[x];
            treeNode.Nodes.Add(new TreeNode(xNode.Name));
            tNode = treeNode.Nodes[x];
            addTreeNode(xNode, tNode);
        }
    }
    else //No children, so add the outer xml (trimming off whitespace)
        treeNode.Text = xmlNode.OuterXml.Trim();
}

XML 文件:

<?xml version="1.0" encoding="utf-8" ?> 
<countries>
    <country>
        <name>India</name>
        <states>
            <state>TamilNadu</state>
            <state>Andhra</state>
            <state>Kerala</state>
            <state>Karnataka</state>
        </states>
    </country>
</countries>

【问题讨论】:

    标签: c# xml winforms treeview linq-to-xml


    【解决方案1】:

    我认为您正在搜索 TreeNode.ImageIndex 属性使用。

    TreeView 的关联ImageList 中存在的Image 分配一个索引

    【讨论】:

    • 能否请您提供更多有关添加图像的详细信息。我检查了它是针对特定数组数据的链接。
    • @linguini: 结帐this 以获取完整示例。
    猜你喜欢
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2021-11-27
    相关资源
    最近更新 更多