简体   繁体   中英

Can't access checked property of menu item created with code outside the designer

private void Form_Shown(object sender, EventArgs e)
{
    // Load Settings
    this.tsmiDuplexEnabled.Checked = Properties.Settings.Default.DuplexEnabled;
    this.tsmiRemoveBlanks.Checked = Properties.Settings.Default.AutoDiscardBlanks;

    this.tsmiColorMode.DropDownItems[Properties.Settings.Default.ColorMode].Checked = true;
}

The last line does not work because it doesn't find the checked property, although there are many available properties. Any idea how I can get at that property?

You need to cast it as a ToolStripMenuItem to get the Checked property. Note that separators are not ToolStripMenuItem so you can't blindly cast every DropDownItem as a ToolStripMenuItem .

For example:

foreach (ToolStripItem tsi in item.DropDownItems)
{
    if (tsi is ToolStripMenuItem)
        ((ToolStripMenuItem)tsi).Checked = true;
}

In your case it looks like you won't accidentally get a separator, so this should work:

((ToolStripMenuItem)this.tsmiColorMode.DropDownItems[Properties.Settings.Default.ColorMode]).Checked = true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM