获取并设置ContextMenuStrip项目

时间:2013-05-05 09:58:57

标签: c# winforms contextmenu menuitem

我在自定义控件中声明了ContextMenuStrip,我似乎找不到控件返回或设置ContextMenuStrip项集合的方法。 我尝试了这段代码,但它不起作用

class Class1 : Panel
{
    ContextMenuStrip _Menu = new ContextMenuStrip();
    public ToolStripItemCollection Items
    {
        get { return _Menu.Items; }
        set { _Menu.Items.AddRange(value); }
    }
}

我怎样才能实现这一目标?

2 个答案:

答案 0 :(得分:0)

// Set  
ContextMenuStrip menu = new ContextMenuStrip();
menu.Items.Add(new ToolStripMenuItem("Item1", aNiceImage, someFunction));
menu.Items.Add(new ToolStripMenuItem("Item2", alsoNiceImage, someOtherFunction));

//Get
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) 
{
   contextMenuStrip1.Items[3].Select();
}

答案 1 :(得分:0)

考试这个:

public partial class Form1 : Form
{
    ContextMenuStrip cms = new ContextMenuStrip();

    public Form1()
    {
        InitializeComponent();
        //cms.Items[;
    }
    public ToolStripItemCollection ConItems
    {
        get
        {
            return cms.Items;
        }
        set
        {
            cms.Items.Clear();
            ToolStripItemCollection tsc=(ToolStripItemCollection)value;
            foreach (ToolStripItem tsi in tsc)
            {
                cms.Items.Add(tsi);
            }
        }
    }

}