问题
I have a menu with checkboxes (for example, Settings > Use HTTP/HTTPS/SOCKS5 - 3 different checkboxes) and I want to make it so that when one checkbox is selected others get unselected automatically.
My idea was to use some kind of loop to go through each element and unselect them except the selected one.
I tried like this:
foreach (ToolStripItem mi in settingsToolStripMenuItem)
{
// code to unselect here
}
But I can't figure it out.
回答1:
In click event handler for sub menu, you can uncheck all items and check only clicked item:
private void SubMenu_Click(object sender, EventArgs e)
{
var currentItem = sender as ToolStripMenuItem;
if (currentItem != null)
{
//Here we look at owner of currentItem
//And get all children of it, if the child is ToolStripMenuItem
//So we don't get for example a separator
//Then uncheck all
((ToolStripMenuItem)currentItem.OwnerItem).DropDownItems
.OfType<ToolStripMenuItem>().ToList()
.ForEach(item =>
{
item.Checked = false;
});
//Check the current items
currentItem.Checked = true;
}
}
Notes:
- You can use the same code for all sub menus, or put it in a function that always ensures only one item is checked and call that function in each sub menu click handler.
- I used
((ToolStripMenuItem)currentItem.OwnerItem)
to find the owner of clicked item to be more general to be reusable for every case you need such functionality.
If there using System.Linq;
is not present in usings of your class, add it.
回答2:
If your checkbox is inside a ToolStripControlHost,
You can do this on the checkbox's CheckedChanged
event:
foreach (ToolStripItem mi in settingsToolStrip.Items) {
ToolStripControlHost item = mi as ToolStripControlHost;
if (item != null) {
if (item.Control is CheckBox) {
// put your code here that checks all but the one that was clicked.
((CheckBox)item.Control).Checked = false;
}
}
}
来源:https://stackoverflow.com/questions/32810730/make-only-one-checkbox-to-be-selected-in-menustrip