开发者

Add checked = true via programming

I have been adding items to tool strip by programming but the issue is that I need to add checked property to it. Do not know how to do so. Here is the code:

toolStripMenuItemAudioSampleRate.DropDownItems.Add("8 kHz", null, new EventHandler(mnuAud开发者_Go百科ioSamplingRate_Click));
toolStripMenuItemAudioSampleRate.Checked = (samplingRate == 8000);//Checks if the there is no vid device

Now I know that it will work wrong because I have added checked property to toolStripMenuItemAudioSampleRate not the 8 kHz. I am trying to add this property to the dynamically added items.

Thanks in advance.


Instead of using the Add(String, Image, EventHandler) helper method to create the drop down item, make your own ToolStripMenuItem, set it to checked, and then add it to the list.

ToolStripMenuItem item = new ToolStripMenuItem("8 kHz", null, new EventHandler(mnuAudioSamplingRate_Click));
item.Checked = (samplingRate == 8000);
toolStripMenuItemAudioSampleRate.DropDownItems.Add(item);


To make this code fancier, I suggest removing new EventHandler, which is always redundant, and using object initializer:

toolStripMenuItemAudioSampleRate.DropDownItems.Add (
    new ToolStripMenuItem ("8 kHz", null, mnuAudioSamplingRate_Click) {
        Checked = (samplingRate == 8000)
    });


toolStripMenuItemAudioSampleRate.DropDownItems["8 kHz"].Checked = (samplingRate == 8000)

That might do what you want. It might be a good idea to hold on to these dynamically added items in an array somewhere, so that you don't have to use this ugly syntax.


You can create an Decorator(GOF Design Pattern) http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/book/hires/pat4dfso.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜