【问题标题】:DesignSurface: Can't delete controlsDesignSurface:无法删除控件
【发布时间】:2015-04-21 21:58:41
【问题描述】:

我目前正在从事一个涉及 DesignSurfaces 的项目。

在 Form_load 事件中,我加载了一个包含 3 个文本框、3 个标签和一个按钮的表单。 为了管理这些控件,我有一个带有菜单项的 ContextMenuStrip,其中包含 StandardCommands 剪切、复制、粘贴和删除。 但是,当我尝试任何这些操作时,它会抛出一个InvalidOperationException,上面写着“无法删除继承的组件'textBox1'”(不幸的是,我没有英文的异常消息,但通过谷歌搜索我发现它可能是这个:“无法删除或销毁继承的组件”) 如果我添加一个控件运行时并尝试删除它,一切正常(剪切、复制、粘贴)。

这是 ContextMenuStrip 的代码:

public void ShowContextMenu( CommandID menuID, int x, int y ) {
            ContextMenu contextMenu = new ContextMenu();

            MenuCommand command = FindCommand( StandardCommands.Cut );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Cut", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }
            command = FindCommand( StandardCommands.Copy );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Copy", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }
            command = FindCommand( StandardCommands.Paste );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Paste", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }
            command = FindCommand( StandardCommands.Delete );
            if( command != null ) {
                MenuItem menuItem = new MenuItem( "Delete", new EventHandler( OnMenuClicked ) );
                menuItem.Tag = command;
                contextMenu.MenuItems.Add( menuItem );
            }

            DesignSurface surface = (DesignSurface) _serviceProvider;
            Control viewService = (Control) surface.View;

            if( viewService != null ) {
                contextMenu.Show( viewService, viewService.PointToClient( new Point( x, y ) ) );
            }
        }


private void OnMenuClicked( object sender, EventArgs e ) {
            MenuItem menuItem = sender as MenuItem;
            if( menuItem != null && menuItem.Tag is MenuCommand ) {
                MenuCommand command = menuItem.Tag as MenuCommand;
                command.Invoke();
            }
        }

我不知道这里有什么问题。

这里有人遇到过类似的问题吗?或者关于如何解决这个问题的任何想法?

【问题讨论】:

  • 哦,对不起,我的意思是“表单加载”事件,而不是“程序加载”事件。我会解决这个问题。
  • 你在主持设计师吗?
  • “托管”是什么意思?
  • 意思是在 Visual Studio 之外提供设计时功能。您在这里使用设计图面,但没有检查系统是否处于设计时,所以我很困惑您如何从服务提供商那里获得设计图面。
  • 我所说的一切都是在运行时。为了创建 designSurface,我使用了 CodeProject 的扩展类:codeproject.com/Articles/24385/…

标签: c# winforms invalidoperationexception


【解决方案1】:

我通过创建一个空表单并手动添加所需的组件来解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-07
    • 2012-04-28
    • 1970-01-01
    • 1970-01-01
    • 2016-11-04
    相关资源
    最近更新 更多