【问题标题】:Make only one checkbox to be selected in menuStrip在 menuStrip 中只选择一个复选框
【发布时间】:2015-09-28 14:03:49
【问题描述】:

我有一个带有复选框的菜单(例如,设置 > 使用 HTTP/HTTPS/SOCKS5 - 3 个不同的复选框),我希望这样当一个复选框被选中时,其他复选框会自动取消选中。

我的想法是使用某种循环来遍历每个元素并取消选择它们,除了选定的元素。

我试过这样:

foreach (ToolStripItem mi in settingsToolStripMenuItem)
            {
                  // code to unselect here
            }

但我想不通。

【问题讨论】:

  • @RezaAghaei 我会在几个小时内试一试,已经离开了,抱歉。

标签: c# winforms checkbox menu


【解决方案1】:

在子菜单的单击事件处理程序中,您可以取消选中所有项目并仅选中单击的项目:

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; 在你的类的使用中不存在,添加它。

【讨论】:

    【解决方案2】:

    如果您的复选框位于 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;
            }
        }
    }
    

    【讨论】:

    • 我收到一个错误:Error 1 foreach statement cannot operate on variables of type 'System.Windows.Forms.ToolStripMenuItem' because 'System.Windows.Forms.ToolStripMenuItem' does not contain a public definition for 'GetEnumerator'
    • 抱歉,复制并粘贴了您的代码,假设它使用正确的代码进行枚举。已编辑。
    • Error 1 The name 'settingsToolStrip' does not exist in the current context。我尝试使用名为settingsToolStripMenuItem 的控件名称,但出现以下错误:Error 1 'System.Windows.Forms.ToolStripMenuItem' does not contain a definition for 'Items' and no extension method 'Items' accepting a first argument of type 'System.Windows.Forms.ToolStripMenuItem' could be found (are you missing a using directive or an assembly reference?)
    猜你喜欢
    • 2017-08-10
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多