【问题标题】:Inherited control will not display in designer继承的控件不会显示在设计器中
【发布时间】:2012-10-09 00:52:15
【问题描述】:

尝试在从 Panel 继承的 C# Winforms 中创建一个简单的自定义控件,但是一旦我将其更改为从“Panel”而不是“UserControl”继承,我就会收到以下错误:

这是整个类的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SETPaint
{
    public partial class Canvas : Panel
    {
        public Canvas()
        {
        InitializeComponent();
        }

        private void Canvas_Load(object sender, EventArgs e)
        {

        }
    }
}

【问题讨论】:

    标签: c# winforms inheritance user-controls


    【解决方案1】:

    删除 Designer.cs 文件中的“this.AutoScaleDimensions = ...”行(根据例外情况,第 35 行)。可能还有另一个类似于“this.AutoScaleMode = .Font”。

    这个问题的出现是因为你在Control派生自UserControl时使用了Designer,并且它在InitializeComponent()方法中设置了一些默认属性。这些属性是 UserControl 基本类型的一部分,但不是 Panel 基本类型的一部分。

    由于 IDE Designer 无法加载 Designer.cs 文件来修复此问题,您需要手动进行。

    【讨论】:

      【解决方案2】:

      你的代码应该是这样的

      using System;
      using System.Collections.Generic;
      using System.ComponentModel;
      using System.Data;
      using System.Drawing;
      using System.Text;
      using System.Windows.Forms;
      
      namespace SETPaint
      {
          public class Canvas : Panel
          {
      
          }
      }
      

      构建解决方案后,工具箱上应该有一个名为 Canvas 的项目

      【讨论】:

      • 对不起,我确实有所有这些 using 语句,但没有将它们包含在原始帖子中,我将其更新为更完整。
      • RJ Lohan 的解决方案有效,我只需要删除那些无效的行。对此解决方案并不完全满意,但显然这是从特定控件而不是用户控件继承时所需要的。
      • @cArn - 您的示例代码暗示 Canvas 控件中不会有 InitializeComponent 方法,但不一定是这种情况,只是隐藏问题而不是修复它。
      • @AdamWathan - 如果您从未在设计器中打开从 UserControl 派生的控件,我相信 IDE 永远不会插入这些错误行。
      猜你喜欢
      • 1970-01-01
      • 2017-04-07
      • 1970-01-01
      • 2010-11-05
      • 1970-01-01
      • 2012-07-17
      • 2013-06-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多