gr Es gr Es - 1 month ago 25
C# Question

Create dynamically nested MenuItem in C#

I would like to know if I can create dynamically a nested MenuItem with C#. To be more precise I have the following code:

public override List<object> ContextMenu
{
get
{

var result = new List<object>
{
new MenuItem
{
Header = "Drive",
Command = Drive_Command,
},
};

var message = new ContextMenuBuild<HostVM>(this);
Messenger.Send(message);
AddExternalContextMenu(result, message.Items);
return result;
}
}


What I want to achieve is a nested MenuItem, the "mySubMenuItem". With wpf would be like this:

<ContextMenu>
<MenuItem Header="Drive" Command="Drive_Command">
<MenuItem Header="mySubMenuItem"/>
</MenuItem>
</ContextMenu>


In order to be able to have a submenu like n the following picture:

enter image description here

Answer

Sure you can.

var mi = new MenuItem(){
    Header = "Drive"
};

var subMi = new MenuItem(){
    Header = "mySubMenuItem"
};
mi.Items.Add(subMi);
Comments