5

I need to change back colours of selected nodes, when node selected and has focus - back color make green, when selected but doesn't have focus - red. 我无法区分关注树视图和不关注树视图的选定节点。位于 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);
}   
4

1 回答 1

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);
    }

PS您可能需要渲染一些您单击以展开节点等的东西。

于 2012-10-15T09:25:26.893 回答