-->

DropDownMenuItem check should uncheck other DropDo

2019-04-16 06:55发布

问题:

I'm creating a ToolStripMenuItem's DropDownItems at runtime.

    Me.mnuExtrasSecondaryLCID.DropDownItems.Clear()

    Dim iCount As Integer = -1

    For Each nLang As clsLanguage In g_LCIDs
        If nLang.IsLeader Then

            iCount += 1

            Dim n As New ToolStripMenuItem
            n.Name = "mnuSecondaryLCID" & iCount.ToString()
            n.Text = nLang.Title
            n.Tag = nLang.LCID
            n.Available = True
            n.CheckOnClick = True

            Me.mnuExtrasSecondaryLCID.DropDownItems.Add(n)

            AddHandler n.Click, AddressOf Me.SecondaryLCIDClick

        End If
    Next

This works fine.

When I then check one of the DropDownItems at runtime, any other DropDownItems in the same "list" stay checked. I would instead like to have only one checked (=the last clicked one).

Is there a property that would let me do this automatically, or do I need to code this by unchecking all other DropDropItems manually?

回答1:

You need to code it manually. When clicking on a sub menu, uncheck all other siblings:

For index = 1 To 5
    Dim subMenu = New ToolStripMenuItem(index.ToString())
    subMenu.CheckOnClick= True
    AddHandler subMenu.Click, Sub(obj, arg)
        Dim item = DirectCast(obj, ToolStripMenuItem)
        For Each sibling In item.Owner.Items.OfType(Of ToolStripMenuItem).Except({obj})
           sibling.Checked = False
        Next sibling
    End Sub
    Menu1ToolStripMenuItem.DropDownItems.Add(subMenu)
Next