使用 Dock 调整用户控件大小后绘图不起作用 None

Drawing does not work after resizing user control with Dock is not None

我有一个非常简单的代码来在我的用户控件上绘制网格(在调用基础 class OnBackgroundPaint 之后):

private void DrawGrid(Graphics g)
        {
            Pen p = new Pen(new HatchBrush(HatchStyle.LargeGrid | HatchStyle.Percent50, Color.LightGray, Color.Transparent), 1);

            for (int i = 0; i < this.Size.Width; i+=50)
            {
                g.DrawLine(p, new Point(i, this.Location.Y), new Point(i, this.Size.Height));
            }

            for (int i = 0; i < this.Size.Height; i += 50)
            {
                g.DrawLine(p, new Point(this.Location.X,i), new Point(this.Size.Width, i));
            }
            p.Dispose();
        }

当我将此控件放置到主窗体上并且不使用停靠时,它可以很好地调整大小。但是,当我将 Dock 属性 设置为 None 以外的任何值时,在调整大小后,绘制的区域将被擦除并且不再绘制。可能是什么原因?

这是因为您必须从 0, 0 位置开始 当您创建用户控件并且想要在其上放置时,您必须从 0、0 左上角位置开始,而不是在父级

上重新分配用户控件
private void DrawGrid(Graphics g)
    {
        Pen p = new Pen(new HatchBrush(HatchStyle.LargeGrid | HatchStyle.Percent50, Color.LightGray, Color.Transparent), 1);

        for (int i = 0; i < this.Size.Width; i+=50)
        {
            g.DrawLine(p, new Point(i, **0**), new Point(i, this.Size.Height));
        }

        for (int i = 0; i < this.Size.Height; i += 50)
        {
            g.DrawLine(p, new Point(**0**,i), new Point(this.Size.Width, i));
        }
        p.Dispose();
    }

您还必须在控件构造函数中调用此函数:

this.SetStyle(ControlStyles.DoubleBuffer | 
    ControlStyles.UserPaint | 
    ControlStyles.AllPaintingInWmPaint,
    true);
this.UpdateStyles();

这个调用告诉用户控件 绘图在缓冲区中进行,完成后将结果输出到屏幕。双缓冲可防止因重绘控件而引起的闪烁。如果将 DoubleBuffer 设置为 true,则还应将 UserPaint 和 AllPaintingInWmPaint 设置为 true。 控件绘制自身而不是操作系统这样做。如果为 false,则不会引发 Paint 事件。此样式仅适用于从 Control 派生的 类。 和 控件忽略 window 消息 WM_ERASEBKGND 以减少闪烁。仅当 UserPaint 位设置为 true 时才应应用此样式。

有关更多信息,您可以查看此 link :

https://msdn.microsoft.com/en-us/library/system.windows.forms.controlstyles(v=vs.110).aspx