简体   繁体   English

尝试从设计类中添加以编程方式在设计时添加到窗体中的winforms控件

[英]Trying to add a winforms control added to form in design time programmatically from a custom class

Ok so I added a contextmenustrip to form1 in a winforms app. 好的,所以我在winforms应用程序中向form1添加了一个contextmenustrip。 I have a standard class elsewhere that takes a treenode as a parameter and does things to it. 我在其他地方有一个标准类,它使用treenode作为参数并对它执行操作。 One of the things I would like to do is set the context menu. 我想做的一件事是设置上下文菜单。 The context menu was added to the form manually at design time. 上下文菜单是在设计时手动添加到表单的。

I have tried things like: 我已经尝试过类似的事情:

public static void MethodThatAddsAContextMenu(TreeNode node)
{
    node.ContextMenuStrip = Application.OpenForms[0].Controls["myContextMenu"] as ContextMenuStrip;
}

And what seems like a million subtle and not so subtle variations. 看起来像一百万微妙而不是那么微妙的变化。 My code doesn't find the control. 我的代码找不到控件。 Although it looks like the context menu isn't actually part of the forms control collection when I drill in via my watch list. 尽管当我通过监视列表进行钻取时,上下文菜单实际上实际上并不是窗体控件集合的一部分。

Any help appreciated. 任何帮助表示赞赏。 Also I did this on my iPad, looks like its formatted ok but apologies if not. 我也是在我的iPad上完成此操作的,看起来格式正确,但如果没有,我深表歉意。

Thanks in advance. 提前致谢。

Ok, Boo as per your suggestion probably easier to just post the code: 好的,Boo根据您的建议可能更容易发布代码:

private static TreeNode CreateSecurityNode(Security Sec)
{
    TreeNode sn = new TreeNode(Sec.SecurityName);
    sn.Tag = Sec;
    sn.ContextMenuStrip = Application.OpenForms[0].Container.Components["securityContext"] as ContextMenuStrip;
}

Container returns null . 容器返回null

ContextMenuStrip would not be part of the Form.Controls collection. ContextMenuStrip将不属于Form.Controls集合。 It is a component, not a control. 它是一个组件,而不是控件。

I would try passing in the ContextMenuStrip with the TreeNode. 我会尝试通过TreeNode传递ContextMenuStrip。

Alternatively you could have your class construct and attach a context menu at runtime. 另外,您可以构造类并在运行时附加上下文菜单。

Also- 也-

You could populate a List<ContextMenuStrip> with all your context menus (or a Dictionary<ContextMenuStrip> ) and expose that as a property of the form: 您可以使用所有上下文菜单(或Dictionary<ContextMenuStrip> )填充List<ContextMenuStrip> ,并将其公开为以下形式的属性:

public List<ContextMenuStrip> contextMenus {get;set;}

// // form load event, possibly
this.contextMenus.Add(myContextMenu);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM