OnLoad 方法适用于 UserControl,但不适用于 Control

Dav*_*rea 4 c# windows-forms-designer

在 Windows 窗体中。

我有一个自定义控件,它只包含一个控件:PictureBox。

public partial class VarIllumButton : UserControl
Run Code Online (Sandbox Code Playgroud)

它使用 OnLoad 方法:

    protected override void OnLoad(EventArgs e) 
    {
        base.OnLoad(e); // Handle the default function
        pictureBox.Image = image0;
    }
Run Code Online (Sandbox Code Playgroud)

由于自定义控件只有1个控件,我希望将其更改为:

public partial class VarIllumButton : PictureBox
Run Code Online (Sandbox Code Playgroud)

但后来我得到一个错误

'System.Windows.Forms.PictureBox' does not contain a definition for 'OnLoad'    
Run Code Online (Sandbox Code Playgroud)

然而,我看到Control 类确实有一个 OnLoad 方法

您能想到为什么我可以从 UserControl 访问它,但不能从 Control 访问它吗?

是否有另一种方法可以在控件完成加载时调用?

Mic*_*rus 5

正如我在评论中提到的,提及的 MSDN 文档OnLoad适用于 Web UI 控件,而不是WinForms 控件。WinForms 没有OnLoad方法。

最好的地方是在构造函数中分配图像,但不幸的是你提到这是不可能的。也许您可以处理OnCreateControl/CreateControl事件,或者您应该让控件的用户在正确的时间分配图像。

我通常建议避免使用Load表单/控件的事件来执行操作,因为在 64 位 Windows 上的 32 位程序中存在异常被吞没的问题 [ SO Q&A文章]。