如何使用TreeViewDrawMode.OwnerDrawAll更改TreeView中所选节点的背景颜色?

时间:2012-10-14 20:50:30

标签: c# .net winforms

我需要更改所选节点的颜色,选择节点并具有焦点 - 背面颜色变为绿色,选中但没有焦点 - 红色。我无法区分选定的节点与焦点在树视图和没有。位于TabPage对象中的树视图。

//...
this.myTreeView.HideSelection = false;
//...
private void myTreeView_drawNode(object sender, DrawTreeNodeEventArgs e)
{
      Color backColorSelected = System.Drawing.Color.Green;
      Color backColor = System.Drawing.Color.Red;
      // node selected and has focus
      if (((e.State & TreeNodeStates.Selected) != 0) 
      && (this.myTabControl.Focused)) // this doesn't work, node is always red
      {
          using (SolidBrush brush = new SolidBrush(backColorSelected))
          {
              e.Graphics.FillRectangle(brush, e.Bounds);
          }
      }
      // node selected but doesn't have focus
      else if ((e.State & TreeNodeStates.Selected) != 0)
      {
          using (SolidBrush brush = new SolidBrush(backColor))
          {
             e.Graphics.FillRectangle(brush, e.Bounds);
          }
      }
      // not selected at all
      else
      {
          e.Graphics.FillRectangle(Brushes.White, e.Bounds);
      }

      e.Graphics.DrawRectangle(SystemPens.Control, e.Bounds);

      TextRenderer.DrawText(e.Graphics,
                             e.Node.Text,
                             e.Node.TreeView.Font,
                             e.Node.Bounds,
                             e.Node.ForeColor);
}   

1 个答案:

答案 0 :(得分:4)

只需检查节点的属性,它就可以工作(测试)。另外我建议缓存你制作的任何自定义画笔,如下所示..(当然你也可以使用Brushes.Red和Brushes.Green)

SolidBrush greenBrush = new SolidBrush(Color.Green);
    SolidBrush redBrush = new SolidBrush(Color.Red);

    private void myTreeView_drawNode(object sender, DrawTreeNodeEventArgs e)
    {
        if (e.Node.IsSelected)
        {
            if (treeView1.Focused)
                e.Graphics.FillRectangle(greenBrush, e.Bounds);
            else
                e.Graphics.FillRectangle(redBrush, e.Bounds);
        }
        else
            e.Graphics.FillRectangle(Brushes.White, e.Bounds);

        e.Graphics.DrawRectangle(SystemPens.Control, e.Bounds);

        TextRenderer.DrawText(e.Graphics,
                               e.Node.Text,
                               e.Node.TreeView.Font,
                               e.Node.Bounds,
                               e.Node.ForeColor);
    }

P.S。您可能需要渲染单击以展开节点等的内容。