简体   繁体   English

将事件处理程序添加到动态添加的MenuItem

[英]Add Event Handler to MenuItem added dynamically

I have a MenuItem . 我有一个MenuItem I have to add sub MenuItem s to this MenuItem . 我必须将子MenuItem添加到此MenuItem But the number of sub MenuItem s is returned through a function. 但是子MenuItem的数量是通过函数返回的。 So, I added the following function which I am calling in the constructor: 因此,我添加了在构造函数中调用的以下函数:

void AddMenuItems()
{
    for (int i = 1; i <= ItemCount(); i++)
    {
        mnuItem.Items.Add(new MenuItem() { Name = "MenuItem" + i, Header = "Menu Item " + i });
    }
}

int ItemCount()
{
    return 3;
}

I hard coded the ItemCount() return value for now. 我现在对ItemCount()返回值进行了硬编码。 What I want now is, how do I add a click event to these menu items. 我现在想要的是如何向这些菜单项添加click事件。

Am I doing this the right way? 我这样做正确吗? Any suggestions as to improve this method are welcome. 欢迎提出任何改进此方法的建议。

You can do the following, change the menu item creation too 您可以执行以下操作,也可以更改菜单项的创建

for (int i = 1; i <= ItemCount(); i++)
{
    var menuItem = new MenuItem() { Name = "MenuItem" + i, Header = "Menu Item " + i };
    menuItem.Click += item_Click;
    mnuItem.Items.Add(menuItem);    
}

And then the click handler will be defined as 然后点击处理程序将被定义为

void item_Click(object sender, RoutedEventArgs e)
{
    //Do stuff
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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