【问题标题】:Calling base class methods from InitializeComponent从 InitializeComponent 调用基类方法
【发布时间】:2013-10-20 01:48:51
【问题描述】:

我正在创建一个基于原型的表单应用程序,其中将有一个用于所有表单的基本模板。模板中有一个方法,需要在实际窗体中调用,同时构造控件。

Form1.cs:

public partial class Form1 : FormBase
{
    public Form1():base()
    {
        InitializeComponent();
    }
    ...

Form1.Designer.cs:

private void InitializeComponent()
{
    this.lblName = new MLabel();
    this.fldName = new MTextBox();
    this.lblUserID = new MLabel();
    this.fldUserID = new MTextBox();

    this.SuspendLayout();

    this.AddControl(lblName, fldName);
    this.AddControl(lblUserID, fldUserID);

FormBase.cs:

public partial class FormBase : Form
{
    public FormBase()
    {
        InitializeComponent();
    }
    protected void AddControl(Label lbl, Control ctrl)
    {
        //do something
    }
    ...

没有编译错误,但是,当我在 IDE 中打开 Form1 设计时,它显示 FormBase.AddControl not found。即使我运行该应用程序,该方法似乎也没有被调用。

谢谢。

【问题讨论】:

  • 从不在 InitializeComponent() 中编辑代码。当设计器重写方法时,您将丢失更改,或者当设计器无法解析您的更改时,您将轰炸设计器。

标签: c# winforms


【解决方案1】:

尝试从Form1.cs调用AddControl方法,不要从Form1.Designer.cs

调用

如果这种方式仍然失败,请告诉我。 :)

【讨论】:

  • 我试图打电话给设计师的目的是我可以在IDE中看到设计,这样我就可以轻松地进行更改。无论如何,我会通过表单调用来检查。
  • 哦,那么你想用你的模板替换 Form1.Designer.cs 的 InitializeComponent 方法中的一些自动生成的部分吗?
  • 不建议将代码放在 InitializeComponent 方法中,因为当您使用设计器 UI 时,它会自动替换。
  • 不建议将代码放在 InitializeComponent 方法中,因为当您使用设计器 UI 时,它会自动替换。但是....当然,它仍然是可能的。只需将 AddControl 方法的访问修饰符更改为 public。现在您可以在设计时看到您的更改。
【解决方案2】:

这是第二个备选:

只需更改这部分

protected void AddControl(Label lbl, Control ctrl)
{
    //do something
}

进入这个:

public void AddControl(Label lbl, Control ctrl)
{
    //do something
}

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 2011-01-05
    • 1970-01-01
    • 2016-10-05
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    相关资源
    最近更新 更多