使用OwnerDrawAll时,windowsforms中的TreeView错误

时间:2009-05-22 13:22:30

标签: c# .net winforms

当使用OwnerDrawAll点击TeeView中的节点时,它不会被选中,直到它收到鼠标,这与标准模式的行为不同,显然不正确。有人有解决方案吗?

运行以下代码以查看此行为:

public partial class Form1 : Form
{
    private System.Windows.Forms.TreeView treeView1;

    public Form1()
    {
        System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Some Node");
        System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Click Me Please!");
        this.treeView1 = new System.Windows.Forms.TreeView();

        this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
        this.treeView1.DrawMode = System.Windows.Forms.TreeViewDrawMode.OwnerDrawAll;
        this.treeView1.FullRowSelect = true;
        this.treeView1.LabelEdit = true;
        treeNode1.Text = "Some Node";
        treeNode2.Text = "Click Me Please!";
        this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {treeNode1, treeNode2});
        this.treeView1.DrawNode += new System.Windows.Forms.DrawTreeNodeEventHandler(this.treeView1_DrawNode);

        Controls.Add(treeView1);
    }

    private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
    {
        Rectangle nodeRect = e.Bounds;
        Rectangle nodeBounds = e.Node.Bounds;

        if (e.Node.IsSelected) {
            e.Graphics.FillRectangle(Brushes.CornflowerBlue, nodeRect);
        }
        else  {
            e.Graphics.FillRectangle(Brushes.White, nodeRect);
        }
        TextRenderer.DrawText(e.Graphics, e.Node.Text, Font, nodeBounds, System.Drawing.Color.Black, Color.Transparent, TextFormatFlags.VerticalCenter | TextFormatFlags.NoClipping);
    }
}

1 个答案:

答案 0 :(得分:0)

Take a look at this page from Microsoft。我将mousedown处理程序和NodeBounds方法添加到您的示例中,它似乎按照预期的方式工作。我想有点麻烦,但它似乎给出了预期的效果。


嗯,你可以试试这个。也许它更好:

private void treeView1_MouseDown(object sender, MouseEventArgs e)
{
   TreeNode clickedNode = treeView1.GetNodeAt(e.X, e.Y);
   if (NodeBounds(clickedNode).Contains(e.X, e.Y))
   {
      if (treeView1.SelectedNode != clickedNode)
      {
         treeView1.SelectedNode = clickedNode;
         treeView1.LabelEdit = false;
      }
      else
      {
         treeView1.LabelEdit = true;
      }
   }
}

我最初设置了treeView1.LabelEdit = false。它似乎更接近你想要的东西。