开发者

Generating a second context menu dynamically in Winforms

开发者 https://www.devze.com 2022-12-30 18:25 出处:网络
I have a context menu with a few selections.If the user picks a particular choice, I want a list of choices 开发者_开发知识库in a second menu to come up.These choices would be coming from a data store

I have a context menu with a few selections. If the user picks a particular choice, I want a list of choices 开发者_开发知识库in a second menu to come up. These choices would be coming from a data store and be unique to that user.

I see how in designer you can add a set of choices statically that show upon the user making a selection. However, what do you do when you need that to come from data and not design it in the designer?


One way is to make a cascading menu: in your context menu, add one item to act as the "parent" item, and add one child menu item to the parent item. Then attach an event handler for the parent item's DropDownOpening event, and add something like this to it:

private void ParentMenuItem_DropDownOpening(object sender, EventArgs e)
{
    IEnumerable<string> items = GetItems();
    _parentMenuItem.DropDownItems.Clear();
    foreach (var item in items)
    {
        _parentMenuItem.DropDownItems.Add(item);
    }
}

This will populate the child menu each time it is opened (add caching as needed).

Technically, this will work without adding the dummy child item, but by adding the child, the parent menu will display the arrow indicating that there is a cascading child menu.


I would add the following to establish event handlers for the new items:

private void ParentMenuItem_DropDownOpening(object sender, EventArgs e)
{
    IEnumerable<string> items = GetItems();
    _parentMenuItem.DropDownItems.Clear();
    int i=0;
    foreach (var item in items)
    {
        _parentMenuItem.DropDownItems.Add(item);
        _parentMenuItem.DropDownItems[i].click += new EventHandler(menuItem_click);
        i++;
    }
}`enter code here`
0

精彩评论

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