当使用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);
    }
}

最佳答案

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。它似乎越来越接近您想要的。

10-07 23:09