简体   繁体   English

如何区分用户控件在窗体上加载和运行时加载

[英]How to distinguish between User Control load on form and load when runtime

I created a user control using C# for windows form application. 我使用Windows窗体应用程序的C#创建了一个用户控件。 This user control has some properties. 此用户控件具有一些属性。 In runtime, if the user does not enter values for this properties I want to show a message box and exit the application. 在运行时,如果用户未输入此属性的值,我想显示一个消息框并退出应用程序。

The problem is when I write the checking code in the Load event of User Control. 问题是当我在用户控件的Load事件中编写检查代码时。 When I drag & drop it on the form the message box will appear. 当我将其拖放到窗体上时,将出现消息框。

private void UserControl1_Load(Object sender, EventArgs e) 
{
    if (_getFirstPageArgument==null || _getFirstPageArgument.Length==0) 
    { 
        throw new Exception("Some Message"); 
    }
}

How do I distinguish between load on the form and load on run time? 如何区分表单上的负载和运行时上的负载?

I fear there is a larger problem here. 我担心这里存在更大的问题。 But to solve your immediate problem (if I understand correctly...) There is a form attribute called DesignMode . 但是要解决您眼前的问题(如果我理解正确...),有一个名为DesignMode的表单属性。 When you are in the visual studio design mode, this will be true . 当您处于Visual Studio设计模式时,这将是true At runtime, this will be false . 在运行时,这将为false

For beginners, @Nimas case can be a good study point to understand that Visual Studio actually runs and executes parts of our code even when we are in design time, which is why the constructor is invoked. 对于初学者来说,@ Nimas案例可以成为一个很好的学习点,以了解即使在设计时,Visual Studio也会实际运行和执行部分代码,这就是调用构造函数的原因。 Even "DesignMode" property is not 100% reliable. 即使“ DesignMode”属性也不是100%可靠的。 You can find an interesting note here related to that http://weblogs.asp.net/fmarguerie/archive/2005/03/23/395658.aspx 您可以在此处找到与此http://weblogs.asp.net/fmarguerie/archive/2005/03/23/395658.aspx相关的有趣注释

If you only want to know when the type itself has been loaded into the runtime (not a specific instance), you can put code into the static constructor for that class. 如果只想知道类型本身何时已加载到运行时中(而不是特定实例),则可以将代码放入该类的静态构造函数中。

If I'm misinterpreting your question, please clarify using a timeline when you want specific events to happen. 如果我误解了您的问题,请在想要发生特定事件时使用时间轴进行说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM