我有一个带有复选框的菜单(例如,Settings >使用HTTP/HTTPS/SOCKS5-3不同的复选框),我希望使它能够在选中一个复选框时使其他复选框自动取消选择。
我的想法是使用某种循环来遍历每个元素并取消对它们的选择,除了选定的元素。
我试过这样做:
foreach (ToolStripItem mi in settingsToolStripMenuItem)
{
// code to unselect here
}但我搞不懂。
发布于 2015-09-28 03:48:25
在单击“子菜单事件处理程序”中,可以取消选中所有项,只检查单击的项:
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;
}
}备注:
((ToolStripMenuItem)currentItem.OwnerItem)来查找单击项的所有者,使其更通用,以便在需要这样的功能的每一种情况下都可以重用。如果类的用法中没有using System.Linq;,那么添加它。
发布于 2015-09-27 18:03:52
如果您的复选框位于ToolStripControlHost中,则可以在复选框的CheckedChanged事件中执行此操作:
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
复制相似问题