没有为子控件调用OnPaint方法 - WinForms

时间:2015-11-04 12:18:18

标签: c# winforms onpaint

我正在使用Control。我在其中添加了两个面板,因为我想在控件上绘制多个面板。我为这两个面板重写了OnPaint()方法,但第一个面板的OnPaint()方法被单独添加到控件中,OnPaint()方法没有调用我添加到控件的第二个面板。

注意:我使用下面的代码重绘表面以避免闪烁问题。如果我从我的示例中删除下面的代码,为第二个面板调用OnPaint()方法,但在第二个面板中绘制的元素不在Visual中。 (即)没有显示。

SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.Selectable |
                     ControlStyles.UserPaint |
                     ControlStyles.AllPaintingInWmPaint, true);

如何在单个控件上实现多个面板?提前谢谢。

代码:

public Class VContainer : Panel

{

public CPanel CPanel;

public SPanel SPanel;

public VContainer()

{

this.CPanel = new CPanel();

this.SPanel = new Spanel();

this.Controls.Add(Cpanel);  **// first added Panel**

this.Controls.Add(SPanel);

}

protected override void OnMouseDown(MouseEventArgs e)

{

this.CPanel.Invalidate();

this.SPanel.Invalidate();

this.SPanel.Update();

}

}

public class CPanel : Panel

{

public CPanel()

{
// Used to redraw the surface to avoid flickering issues
SetStyle(ControlStyles.OptimizedDoubleBuffer |
                           ControlStyles.UserPaint |
                           ControlStyles.AllPaintingInWmPaint, true);

}

**// OnPaint() called since Cpanel is added first to the VContainer**

protected override void OnPaint(PaintEventArgs e)

{
e.Graphics.FillRectangle(Brushes.Red, new Rect(0,0,50,50));

base.OnPaint(e);

}

}

public class SPanel : Panel

{

public SPanel()

{
// Used to redraw the surface to avoid flickering issues
SetStyle(ControlStyles.OptimizedDoubleBuffer |
                           ControlStyles.UserPaint |
                           ControlStyles.AllPaintingInWmPaint, true);
}

**// OnPaint() method is not called while invalidating the Panel since the Spanel is added as second control to VContainer**

protected override void OnPaint(PaintEventArgs e)

{
e.Graphics.FillRectangle(Brushes.Green, new Rect(0,0,50,50));

base.OnPaint(e);

}

}

1 个答案:

答案 0 :(得分:0)

卡特桑,

您的两个控件CPanelSPanel处于同一位置。

因此,一个与另一个重叠,Winforms不会在下面绘制一个。

更改控件的位置和大小,您会看到一些内容:

public VContainer()
{
    this.CPanel = new CPanel();
    CPanel.Top = 0;
    CPanel.Left = 0;
    CPanel.Width = 50;
    CPanel.Height = 50;
    this.Controls.Add(CPanel);  // first added Panel**


    this.SPanel = new SPanel();
    SPanel.Top = 50;
    SPanel.Left = 50;
    SPanel.Width = 50;
    SPanel.Height = 50; 
    this.Controls.Add(SPanel);
}

顺便说一下,改变OnPaint方法指令的顺序 因为如果基类进行了一些绘制,它将涵盖你所做的事情:

protected override void OnPaint(PaintEventArgs e)
{
    base.OnPaint(e);
    e.Graphics.FillRectangle(Brushes.Red, new Rectangle(0, 0, 50, 50));
}

工作解决方案的完整来源:http://1drv.ms/1NtIttW

此致