C# 将复选框添加到 WinForms 上下文菜单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1069687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# Add Checkbox To WinForms Context Menu
提问by Goober
I have a series of checkboxes on a form. I want to be able to select these from a context menu as well as the form itself. The context menu is linked to the system tray icon of the application.
我在表单上有一系列复选框。我希望能够从上下文菜单以及表单本身中选择这些。上下文菜单链接到应用程序的系统托盘图标。
My question is, is it possible to link the context menu to these checkboxes? Or even possible to add checkboxes to the context menu? Or even a combination?!
我的问题是,是否可以将上下文菜单链接到这些复选框?或者甚至可以在上下文菜单中添加复选框?甚至是组合?!
采纳答案by Fredrik M?rk
The menu items have a Checked
property (MenuItem.Checked
, ToolStripMenuItem.Checked
) that you can use for this purpose.
菜单项具有可用于此目的的Checked
属性 ( MenuItem.Checked
, ToolStripMenuItem.Checked
)。
Regarding the possibility to link the context menu items to the check boxes, if you use a ContextMenuStrip
and set CheckOnClick
property to true
, you can hook up the CheckedChanged
events to the same event handler for the ToolStripMenuItem
and CheckBox
controls that should be "linked", and inside that event handler make sure to synchronize the Checked
property of the controls and perform any other needed actions.
关于将上下文菜单项链接到复选框的可能性,如果您使用 aContextMenuStrip
并将CheckOnClick
属性设置为true
,则可以将CheckedChanged
事件连接到应该“链接”的ToolStripMenuItem
和CheckBox
控件的相同事件处理程序,并在该事件处理程序内部确保同步Checked
控件的属性并执行任何其他需要的操作。
回答by Dmitry Brant
Well, a menu item has the "Checked" property, which can make it behave like a checkbox. When you click a menu item, you can programmatically toggle the state of the corresponding checkbox on your form.
好吧,菜单项具有“Checked”属性,这可以使其表现得像一个复选框。当您单击菜单项时,您可以以编程方式切换表单上相应复选框的状态。
You can also use the Opening event of the context menu to set the Checked state of the menu items based on the checked state of the checkboxes.
您还可以使用上下文菜单的 Opening 事件根据复选框的选中状态设置菜单项的选中状态。
回答by Ehz
You can host standard as well as custom controls by wrapping them in a ToolStripControlHost
您可以通过将它们包装在 ToolStripControlHost 中来承载标准和自定义控件
http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripcontrolhost.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstripcontrolhost.aspx
回答by shawn
//Create the combo box object and set its properties
cmbFunctionArea = new ComboBox();
cmbFunctionArea.Cursor = System.Windows.Forms.Cursors.Arrow;
cmbFunctionArea.DropDownStyle=System.Windows.Forms.ComboBoxStyle.DropDownList;
cmbFunctionArea.Dock = DockStyle.Fill;
//Event that will be fired when selected index in the combo box is changed
cmbFunctionArea.SelectionChangeCommitted += new EventHandlercmbFunctionArea_SelectedIndexChanged);