Summary of the problem
Goal
My goal is to create a Navigation menu in WPF.
The navigation items are built in the View Model using Nodes.
Selected SubItem of the menu will display the content of the selected Node.
Expected and actual result
This is what I have built so far:
Error
Now I need to present the selected MenuItem to ContentPresenter - and this is where I have the problem with.
What I have tried
This is my current code
XAML
<!--Menu-->
<Menu x:Name="NavigationTreeView" IsMainMenu="True" ItemsSource="{Binding Navigation}" Grid.Row="0">
<Menu.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding Path=Title}" />
<Setter Property="Template" Value="{StaticResource VsMenuTop}" />
</Style>
<HierarchicalDataTemplate DataType="{x:Type nav:PageViewModel}" ItemsSource="{Binding Children}" />
</Menu.Resources>
</Menu>
<!--Content-->
<ContentPresenter Grid.Row="1" Content="{Binding ElementName=NavigationTreeView, Path=SelectedItem.Content}" />
This will not work, because I am not able to bind it to Menu using this line here: SelectedItem.Content - and the Menu does not have a property SelectedItem.
Alternative
My alternative option would be to use ListView, because it contains a property SelectedItem. But preferably I'd like to use Menu.
Question
How can I get the selected item from the Hierarchical Data Template?

The
Menucontrol does not have a notion of a selected item, as itsMenuItems are essentially buttons that should execute an action when clicked. You can set theIsCheckableproperty totrueto be a able to check menu items like aCheckBox, but I guess that does not fit your use-case here.Since you probably want to display different content depending on which menu item was clicked, you could use a command, that is executed when you click a
MenuItemand gets the corresponding view model as parameter and sets a property on a view model that can be bound by theContentPresenter.Introduce a
Selectedproperty of typePageViewModeland aSelectcommand in your main view model that contains theNavigationporperty. The command sets theSelectedproperty.You can replace the
RelayCommandby the command implementation that you have at your disposal.Then, you can adapt your style to bind the command on the main view model (either using
ElementNameorRelativeSourceto the data context) and to bind the view model of the clickedMenuItemas command parameter. This way it is passed to the command, which sets it asSelected.Bind the
Contentof yourContentPresenterto theSelectedproperty on the main view model.