tags:

views:

328

answers:

1

When clicking on a node in a TeeView using OwnerDrawAll it does not get selected until it receives a mouse up which is a different behavior from the standard mode and obviously not correct. Does anyone have a solution to this?

Run the code below to see this behaviour:

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

Take a look at this page from Microsoft. I added the mousedown handler and the NodeBounds method to your example and it seemed to work as one would expect. A bit of a hassle, I suppose, but it seemed to give the desired effect.


Well, you could try this. Perhaps it is better:

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

I just set treeView1.LabelEdit = false initially. And it seemed to get closer to what you want.

itsmatt
Thanks, but this does not solve the issue because when you click on a node label it always becomes editable. Which is not the way it's supposed to be a label should become editable when you click on an node that has already been selected
Take a look at my added code. It seemed to work a bit better.
itsmatt