Treeview draw glitch

2019-06-18 12:18发布

问题:

I implemented a multicolor system for each of my TreeView nodes. But everytime I expand a child node, it expends but also paints the node over my rootNode (image 2 and 3). The code is from my previous question and this is what the bug looks like

If I decide to close every node and re-expand the glitch is gone.(image 4)

The problem Seems to be with the Bounds that's why the draw isn't at the right place. Any idea why ?


  private void treeView1_DrawNode(object sender, DrawTreeNodeEventArgs e)
  {
    string[] texts = e.Node.Text.Split();
    using (Font font = new Font(this.Font, FontStyle.Regular))
    {
        using (Brush brush = new SolidBrush(Color.Red))
        {
            e.Graphics.DrawString(texts[0], font, brush, e.Bounds.Left, e.Bounds.Top);
        }

        using (Brush brush = new SolidBrush(Color.Blue))
        {
            SizeF s = e.Graphics.MeasureString(texts[0], font);
            e.Graphics.DrawString(texts[1], font, brush, e.Bounds.Left + (int)s.Width, e.Bounds.Top);
        }
    }
  }

回答1:

Drawing glitch seems to be an accurate description.

You can try this work around by subscribing to the AfterExpand event:

void treeView1_AfterExpand(object sender, TreeViewEventArgs e) {
  treeView1.Invalidate();
}


回答2:

Just Make Sure To Use : "BeginUpdate()" and "EndUpdate()" Everytime You Populate the TreeView

The "EndUpdate()"<- Is the Most Important thing to Get Rid this Kind of Glitch!

Good Luck! :)

Cheers, J