C# 菜单项添加复选标记

在网上查找都是说直接用菜单项的Checked属性,

toolMenuItem.Checked=!toolMenuItem.Checked;

但是我用了也切换不过来。

有点晕菜了,我用的是vs2017.

最后自己摸索弄出下面的方法,但是没能理解其含义。也是醉了。

在菜单项的点击事件中,判断菜单项的选中状态

//窗体置顶
private
void TOPFORM_ToolStripMenuItem_Click(object sender, EventArgs e) { ToolStripMenuItem toolMenuItem = sender as ToolStripMenuItem; if (toolMenuItem.CheckState==CheckState.Unchecked) { toolMenuItem.CheckState = CheckState.Unchecked;//菜单项取消选中标记 toolStripButton5.CheckState = CheckState.Unchecked;//对应工具栏上的按钮也取消选中标记 } else { toolMenuItem.CheckState = CheckState.Checked; toolStripButton5.CheckState = CheckState.Checked; } }

我也不太明白为啥是选中状态==取消状态(Unchecked)才能切换选中的勾

但是只有这样写才能切换选中状态

如果写成:

private void TOPFORM_ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem toolMenuItem = sender as ToolStripMenuItem;

            if (toolMenuItem.CheckState==CheckState.Unchecked)
            {
              
                toolMenuItem.CheckState = CheckState.Checked;
                toolStripButton5.CheckState = CheckState.Checked;
            }
            else
            {
    
                toolMenuItem.CheckState = CheckState.Unchecked;
                toolStripButton5.CheckState = CheckState.Unchecked;          
        } }

就不行,切换不了

签名:GreenLeaf1976
原文地址:https://www.cnblogs.com/greenleaf1976/p/14928610.html