c# - 将 ToolStripMenu 重新用于 ToolStrip 或 ContextMenuStrip?

标签 c# winforms user-interface menu

在我的应用程序中,我有一个 ToolStripMenu(文件、编辑、注释)、一个位于我的工作区上方的 ToolStrip 和一个工作区本身的上下文菜单。现在,Notes ToolStripMenu、ToolStrip 和 ContextMenuStrip 都具有执行相同操作的相同内容。我想知道,是否有一种优雅的方法来设计 ToolStripMenu 并让其他两个“镜像”它的功能和内容,而不是重写所有内容 3 次?我看到所有 3 个控件都使用 ToolStripItems 和 ToolStripItemCollections,因此我认为这很容易做到,但属性大多是只读的,如果我尝试遍历一个项目以将它们添加到另一个,它们是从初始所有者中删除,并且 ToolStripItems 没有 Clone 方法。

谢谢。

最佳答案

创建一个重用您的项目、操作等的方法...

public MainForm()
{
    //in your constructor, create all your common methods, actions, etc and save them to private vars

    //Then in your form:
    ToolStripMenu menu = new ToolStripMenu();
    AttachCommonFunctionality(menu);
    Items.Add(menu);

    ContextMenuStrip rightClick = new ContextMenuStrip();
    AttachCommonFunctionality(rightClick);
    this.ContextMenu = rightClick;
    //etc...
}

private void AttachCommonFuntionality(Control c)
{
    c.Items.Add(_item1);
    c.Items.Add(_item2);
    //etc...

    c.OnClick += _myCommonAction;
    //etc...
}

关于c# - 将 ToolStripMenu 重新用于 ToolStrip 或 ContextMenuStrip?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3086269/

相关文章:

c# - T4 模板错误 : loading the include file ef. utility.cs.ttinclude 返回了 null 或空字符串

c# - 使用哪个,C# 还是 F#?在这个 "real world"案例中

ios - 在 Swift 中以编程方式设置 UI 约束(UIView 中的图像和 stackView)

c++ - 在 QTCreator GUI 中播放视频

c# - 有效地拆分格式为 "{ {}, {}, ...}"的字符串

c# - 如何创建同时面向 .NET 2.0 和 .NET Standard 的库?

c# - 如何避免用户帐户控制或在 Win7 中始终以管理员模式运行 Windows 应用程序

c# - 将字符串从 datagridview 传递到另一种形式的文本框

c# - 如何修复winform中的 "inaccessible due to its protection level"错误?

c# - 如何为我的 .NET Windows 应用程序提供专业的外观和感觉?