I have a MenuItem
. I have to add sub MenuItem
s to this MenuItem
. But the number of sub MenuItem
s is returned through a function. 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. What I want now is, how do I add a click event to these menu items.
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
}
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.