In WPF, we work with data elements whose public properties are data bound to the properties of various UI controls via DataTemplate
s. Please see the Data Templating Overview page on MSDN for the full story.
In order to do this, we develop custom classes that contain all of the necessary properties that we need to display and then we declare one or more DataTemplate
s that define the binding connections between the classes and the UI controls, or MenuItem
s in your case.
The benefit of this is that in order to display a Menu
in the UI, you just need to data bind one of your custom menu class objects to a control in the UI and let the DataTemplate
do the rest. So if you want to change the menu contents, you just need to change the data item that is data bound to the Menu
.
So to answer your question directly, a Menu
control would be most suitable for you to use, but you don't store the Menu
properties in your code behind... you store the property values in your custom classes that will be data bound to the Menu
control properties:
<Menu ItemsSource="{Binding CollectionOfYourCustomClassItems}" ... />
It is worth pointing out that you may need to set the child MenuItem
properties in a Style
and not a DataTemplate
as usual (taken from the accepted answer to the WPF MenuItem : Mix databound items and static content question (which I recommend that you read) here on Stack Overflow):
<MenuItem Header="_Recent Files" ItemsSource="{Binding Commands,Mode=OneWay}">
<MenuItem.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Path=ShortName}" />
<Setter Property="ToolTip" Value="{Binding Path=FileName}" />
<Setter Property="Command" Value="{Binding Path=OpenCommand}" />
<Setter Property="CommandParameter" Value="{Binding Path=OpenParameter}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSeparator}" Value="true">
<Setter Property="MenuItem.Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MenuItem}">
<Separator Style="{DynamicResource {x:Static MenuItem.SeparatorStyleKey}}"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</DataTrigger>
</Style.Triggers>
</Style>
</MenuItem.ItemContainerStyle>
</MenuItem>
You will find many more tutorials and related questions regarding data binding to MenuItem
s online, so I won't go over everything again here. Please see the following article to start with:
Binding menus using HeirarchicalDataTemplates