【问题标题】:Designer and inherited ContextMenuStrip设计器和继承的 ContextMenuStrip
【发布时间】:2013-04-11 06:36:20
【问题描述】:

我有一个问题,设计师没有将继承的ContextMenuStrip 添加到components。以下是重现问题的方法:

  1. 创建新项目(Windows 窗体应用程序)。
  2. 通过设计器添加到表单ContextMenuStrip,它将生成:

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
        ...
    }
    
  3. 创建MyContextMenuStrip 类:

    public class MyContextMenuStrip : ContextMenuStrip
    {
    }
    
  4. 通过设计器编译并添加到表单MyContextMenuStrip,它将生成:

    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
        this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
        this.myContextMenuStrip1 = new WindowsFormsApplication1.MyContextMenuStrip();
        ...
    }
    

WTF?为什么不给组件添加MyContextMenuStrip???

我需要在components 中为我的本地化经理提供菜单(以自动翻译菜单)。我是否忘记了某些属性、接口或覆盖?

【问题讨论】:

    标签: winforms designer contextmenustrip


    【解决方案1】:

    Visual Studio 没有使用Container 初始化您的MyContextMenuStrip,因为您的控件没有接受Container 作为参数的构造函数。

    在您的MyContextMenuStrip 中创建一个构造函数,该构造函数采用System.ComponentModel.IContainer,然后使用base 关键字将此参数传递给控件的基类:

    class MyContextMenuStrip : ContextMenuStrip
    {
        public MyContextMenuStrip(System.ComponentModel.IContainer c) : base(c) { }
    }
    

    这样做之后你会发现,当你使用设计器将MyContextMenuStrip 添加到表单时,VS 会在你的表单的InitializeComponent 方法中生成你想要的代码:

    this.myContextMenuStrip1 = new WindowsFormsApplication1.MyContextMenuStrip(this.components);
    

    【讨论】:

    • 谢谢,已经采取了另一种方式(枚举控件并检查它们的Control.ContextMenuStrip),但效果不佳(如果MyContextMenuStrip 未分配给任一控件并假设显示以编程方式 - 然后我找不到它).. 然后你来到这里 =D
    • @Sinatr 谢谢你,我学到了一些东西,你的问题很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 2019-09-29
    • 2016-10-06
    • 1970-01-01
    相关资源
    最近更新 更多