Sunday, April 3, 2011

OnPaint method is being call for every child control.

I've a UserControl (WinForms, .net 2.0), and I've this:

protected override void OnPaint(PaintEventArgs e)
{
 base.OnPaint(e);

 var rect = e.ClipRectangle;
 var pen = new Pen(Brushes.LightGray, 1);

 e.Graphics.DrawRectangle(pen, rect);
}

I basically want to draw a border on the UserControl, but the rectangle is being draw in all the child controls too! I never read it should be called for every child control, is there a solution?

From stackoverflow
  • Why are you using PaintEventArgs.ClipRectangle to determine the bounds of the rectangle? Try using Control.ClientRectangle instead.

  • Because the child controls invalidate the parent, causing this method to be fired for each one.

    Instead of using e as the parameter (e is going to be whichever control fired the event, child or not) use the control name explicity.

0 comments:

Post a Comment