猿问

C# 主窗体引用异常

我做了一个 UserControl 并想添加 MainForm Reference


  public partial class ConsolePage : UserControl

{

    public synForm mainForm = new synForm();


    public ConsolePage(synForm parentForm)

    {

        mainForm = parentForm();

        InitializeComponent();

    }

所以,问题是,只要我在 c# 代码中创建我的 UserControl(无论在哪里),它都可以完美运行,但是当我尝试从 Toolbox 的 Designer 中添加他时,我得到了一个异常。


我知道,我应该这样称呼他们


MyControl whatever = new MyControl(this); 

我知道如果我想从 Toolbox 添加 myControl ,我应该在我的 Form.Designer 中更正它!


不要恨我,我是编程和拼写的新手 :D


编辑:<<<<<<<


忘了说我得到了什么错误:


System.ComponentModel.Design.Serialization.DesignerSerializationManager.CreateInstance(类型类型,ICollection 参数,字符串名称,布尔型 addToContainer)


System.ComponentModel.Design.Serialization.DesignerSerializationManager.System.ComponentModel.Design.Serialization.IDesignerSerializationManager.CreateInstance(类型类型,ICollection 参数,字符串名称,布尔型 addToContainer)


System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeInstance(IDesignerSerializationManager manager, Type type, Object[] parameters, String name, Boolean addToContainer)


System.ComponentModel.Design.Serialization.ComponentCodeDomSerializer.DeserializeInstance(IDesignerSerializationManager manager, Type type, Object[] parameters, String name, Boolean addToContainer)


System.ComponentModel.Design.Serialization.CodeDomSerializerBase.DeserializeExpression(IDesignerSerializationManager manager, String name, CodeExpression expression)


System.ComponentModel.Design.Serialization.CodeDomSerializer.DeserializeStatementToInstance(IDesignerSerializationManager manager, CodeStatement statement)

 System.ComponentModel.Design.Serialization.CodeDomSerializer.Deserialize(IDesignerSerializationManager manager, Object codeObject)

bei System.Windows.Forms.Design.ControlCodeDomSerializer.Deserialize(IDesignerSerializationManager manager, Object codeObject)


System.ComponentModel.Design.Serialization.TypeCodeDomSerializer.DeserializeName(IDesignerSerializationManager manager, String name, CodeStatementCollection statements) 


慕村225694
浏览 265回答 1
1回答

白衣非少年

在不知道错误消息(您只提供堆栈跟踪)和 parentForm() 的内容的情况下,说起来并不容易。但似乎 parentForm() 正在做一些在设计器中不可能的事情。因此,您可以通过检查 DesignMode ( https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.component.designmode?redirectedfrom=MSDN&view=netframework-4.7 .2#System_ComponentModel_Component_DesignMode)。public ConsolePage()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (!DesignMode)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; mainForm = parentForm();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; InitializeComponent();&nbsp; &nbsp; }
随时随地看视频慕课网APP
我要回答