首页 > 解决方案 > 奇怪的行为 OnPaint/OnLayout

问题描述

我有一个网格和一个四边形。其中的网格布局四边形。

class Grid : System.Windows.Forms.Control
    {
        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
        }

        protected override void OnLayout(LayoutEventArgs levent)
        {
            base.OnLayout(levent);

            int numControls = this.Controls.Count;

            if (numControls < 1)
            {
                return;
            }

            int size = this.Width / numControls;

            int i = 0;

            foreach (Control ctrl in this.Controls)
            {
                ctrl.Size = new Size(size, this.Height);
                ctrl.Location = new Point(i * size, 0);
                i++;
            }
        }
}

class Quad : System.Windows.Forms.Control
    {
        protected override void OnPaint(PaintEventArgs args)
        {
            base.OnPaint(args);

            Pen p = new Pen(new SolidBrush(Color.Black));

            int x = this.ClientRectangle.X;
            int y = this.ClientRectangle.Y;
            int w = this.ClientRectangle.Width;
            int h = this.ClientRectangle.Height;

            args.Graphics.DrawRectangle(p, x,y,w-1,h-1);
        }
    }

在我的表格中

        this.quad1 = new Quad();
        this.SuspendLayout();

        grid1 = new Grid();
        grid1.Size = new Size(200, 200);

        for (int i = 0; i < 4; i++)
        {
            Grid grid_j = new Grid();
            for (int j = 0; j < 4; j++)
            {
                grid_j.Controls.Add(new Quad());
            }
            grid1.Controls.Add(grid_j);
        }

        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.ClientSize = new System.Drawing.Size(284, 261);
        this.Controls.Add(grid1);
        this.Name = "Form1";
        this.Text = "Form1";
        this.ResumeLayout(false);

protected override void OnLayout(System.Windows.Forms.LayoutEventArgs levent)
        {
             base.OnLayout(levent);

             this.grid1.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);
             this.grid1.Location = new Point(0, 0);
        }

但是,这根本不起作用。一旦调整整个事物的大小,就会绘制出疯狂的图案。

疯狂的模式

这是为什么?我尝试清除图形但没有成功(我认为它会在 OnPaint 之前自动清除?)。

似乎添加“无效”调用可以解决问题:

foreach (Control ctrl in this.Controls)
            {
                ctrl.Size = new Size(size, this.ClientRectangle.Height-10);
                ctrl.Location = new Point(i * size, 0);
                ctrl.Invalidate();
                i++;
            }

这是正确的方法吗?另外,我什么时候必须调用进一步的“更新”?

标签: c#.netwinformsonpaint

解决方案


推荐阅读