2013-11-21 26 views
2

我如何改变正负TreeView控件图标使用C#.NET一些其他的图标。树视图:更改正负图标

+0

任何努力这么远? –

+0

可能的重复[如何更改我的treeView图标insted的+, - 像c#.net win窗体中的Windows资源管理器树视图](http://stackoverflow.com/questions/13625420/how-to-change-my-treeview -icons-insted-like-a-windows-explorer-treeview -i) –

回答

8

当你想自定义你的treeview控件时,Microsoft在treeview控件上提供了一个名为“TreeViewDrawMode”的属性,它的值是一个枚举,它有3个值:Normal,OwnerDrawText和OwnerDrawAll,在你的情况下,你必须使用OwnerDrawAll 。在将该属性设置为OwnerDrawAll后,当显示树视图的节点时,将触发名为“DrawNode”的事件,以便您可以在那里处理您的绘图。当你自己绘制它时,通常需要绘制3件东西:展开/折叠图标,节点图标,节点文本。 我的样品低于:

//define the icon file path 
    string minusPath = Application.StartupPath + Path.DirectorySeparatorChar + "minus.png"; 
    string plusPath = Application.StartupPath + Path.DirectorySeparatorChar + "plus.png"; 
    string nodePath = Application.StartupPath + Path.DirectorySeparatorChar + "directory.png"; 

    public FrmTreeView() 
    { 
     InitializeComponent(); 
     //setting to customer draw 
     this.treeView1.DrawMode = TreeViewDrawMode.OwnerDrawAll; 
     this.treeView1.DrawNode += new DrawTreeNodeEventHandler(treeView1_DrawNode); 
    } 

    void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e) 
    { 
     Rectangle nodeRect = e.Node.Bounds; 
     /*--------- 1. draw expand/collapse icon ---------*/ 
     Point ptExpand = new Point(nodeRect.Location.X - 20, nodeRect.Location.Y + 2); 
     Image expandImg = null; 
     if (e.Node.IsExpanded || e.Node.Nodes.Count < 1) 
      expandImg = Image.FromFile(minusPath); 
     else 
      expandImg = Image.FromFile(plusPath); 
     Graphics g = Graphics.FromImage(expandImg); 
     IntPtr imgPtr = g.GetHdc(); 
     g.ReleaseHdc(); 
     e.Graphics.DrawImage(expandImg, ptExpand); 

     /*--------- 2. draw node icon ---------*/ 
     Point ptNodeIcon = new Point(nodeRect.Location.X - 4, nodeRect.Location.Y + 2); 
     Image nodeImg = Image.FromFile(nodePath); 
     g = Graphics.FromImage(nodeImg); 
     imgPtr = g.GetHdc(); 
     g.ReleaseHdc(); 
     e.Graphics.DrawImage(nodeImg, ptNodeIcon); 
     /*--------- 3. draw node text ---------*/ 
     Font nodeFont = e.Node.NodeFont; 
     if (nodeFont == null) 
      nodeFont = ((TreeView)sender).Font; 
     Brush textBrush = SystemBrushes.WindowText; 
     //to highlight the text when selected 
     if ((e.State & TreeNodeStates.Focused) != 0) 
      textBrush = SystemBrushes.HotTrack; 
     //Inflate to not be cut 
     Rectangle textRect = nodeRect; 
     //need to extend node rect 
     textRect.Width += 40; 
     e.Graphics.DrawString(e.Node.Text, nodeFont, textBrush, Rectangle.Inflate(textRect, -12, 0)); 
    } 

the result of my test

+0

当我展开treeview时它从根节点渲染文本也 –

+1

嗨Vignesh,我想你需要调整文本的位置点。 –

+0

我尝试了上面的示例代码,但它对我造成了一个错误。如果我点击任何节点,它将绘制该节点的位置,并绘制第一个根节点。我想停止在第一个根节点上绘制的子节点。这是我的输出屏幕https://s1.postimg.org/84fhr5dnf3/treeview.png –