【问题标题】:TreeView : Change Plus Minus icon [closed]TreeView:更改加减号图标[关闭]
【发布时间】:2013-11-21 15:33:17
【问题描述】:

如何使用 C#.NetTreeView ControlPlus Minus 图标更改为其他图标。

【问题讨论】:

标签: c# winforms visual-studio-2010 tree treeview


【解决方案1】:

当你想自定义你的TreeView控件时,微软在TreeView控件上提供了一个名为TreeViewDrawMode的属性,它的值是一个枚举,它有3个值:NormalOwnerDrawTextOwnerDrawAll,根据你的情况,您必须使用OwnerDrawAll

将该属性设置为TreeViewDrawMode.OwnerDrawAll 后,当TreeView 的节点显示时,将触发一个名为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));
}

【讨论】:

  • 当我展开树视图时,它也会从根节点呈现文本
  • 嗨 Vignesh,我猜你需要调整文本的位置点。
  • 我尝试了上面的示例代码。但它对我来说会导致错误。如果我单击任何节点,它将在该节点位置上绘制并在第一个根节点上绘制。我想停止子节点在第一个根节点上绘制。这是我的输出屏幕s1.postimg.org/84fhr5dnf3/treeview.png
  • 嗨 Vignesh,很抱歉回复晚了,我想您已经知道了,如果没有,请通过链接或邮件给我您的代码。
  • if (e.Node.Bounds.X != 0 ) { //Drawnode 逻辑写在这个条件里面然后它的工作好 }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-27
  • 2012-02-10
  • 1970-01-01
  • 2020-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多