C# 帮助为 MenuStrip 添加单选按钮/选项按钮按钮、单选、选项、MenuStrip

2023-09-06 19:28:02 作者:丿风暴☆皇族灬

我是 C# 语言的初学者,所以我需要一些天才的帮助:我需要为菜单条添加一个单选按钮.我已经将 CheckOnClick 属性更改为 true,但我需要一个用于单选按钮选择的选项.您可以从 Windows 计算器菜单栏中看到它(单击查看).如何通过 MenuStrip 属性访问它?

I'm a beginner in C# language, so I need some help from the geniuses with this scheme: I need to add a radio button for a menu strip. I've already changed the, CheckOnClick property to true, but I need an option for radio button selection. You can see it from the Windows calculator menu bar (click View). How can I get to it via the MenuStrip property?

推荐答案

我知道这是一个近乎古老的帖子,但我认为值得一提的是,虽然没有对 RadioButton MenueItem 的原生支持,但很容易哄他们复选框的行为方式.首先将每个 MenueItem 的 CheckOnClick 属性设置为 FALSE.然后将相同的 MouseDown 事件处理程序应用于每个项目:

I know this is a near-ancient post, but I thought it worth mentioning that although there's no native support for a RadioButton MenueItem, it's easy enough to coax their checkboxes into behaving that way. Start by setting the CheckOnClick property of each MenueItem to FALSE. Then apply the same MouseDown event handler to each item:

private void ToolStripMenueItem_MouseDown(object sender, MouseEventArgs e)
{
    var thisTsmi = (ToolStripMenuItem)sender;
    foreach (ToolStripMenuItem tsmi in thisTsmi.GetCurrentParent().Items)
    {
        tsmi.Checked = thisTsmi == tsmi;
    }
}

您可以改用 Click 事件,但我更喜欢 MouseDown 因为它为用户提供了一些可视化,即在离开 Click 时选中的项目已更改 事件打开以根据需要对单个项目进行编码.

You could use the Click event instead, but I prefer MouseDown because it provides some visualization to the user that the checked item has changed while leaving the Click event open for coding the individual items if needed.