c# - 奇怪的行为 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++;
}
这是正确的方法吗?另外,我什么时候必须调用进一步的“更新”?
解决方案
推荐阅读
- postman - 如何通过“从 URL 插入”curl 选项将邮递员 curl 代码转换为 filemaker pro?
- javascript - 自定义 Antd AutoComplete 以将 {children} 用于 dataSource 和 input
- docker - 如何从另一个 docker 容器使用在 docker 容器上运行的模拟器?
- typescript - Electron-renderer 不会从文件或 webpack-dev-server 加载 webpack 包
- tensorflow - 节点和操作之间的区别
- reactjs - 我想在模拟 promise 方法时返回两个不同的响应
- python - 我想在 RSS 提要描述标签中获取图片链接
- javascript - 如何根据标签等条件删除子元素,
- c# - IIS 应用程序池已关闭,事件 ID 为 5009
- java - Hibernate & MariaDB auto_increment 没有通过级联正确设置 FK