Customize the menu depending on situation in WPF
How can I customize the menu to the situation in WPF? I have a main window with a basic menu. In this window, I can load different UserControls and then I want the menu to be expanded with different menu options depending on which User Control is used.
Example:
Main menu:
File
Open
-
MRU
-
Exit
For viewing of UserControl 1:
File
Open
Edit
-
MRU
-
Exit
For viewing of UserControl 2:
File
Open
Edit
-
MRU
开发者_StackOverflow社区-
Exit
View
Show codes
Show capital letters
In Editing
File
Open
Save
Save as...
-
MRU
-
Exit
Edit
Add
Remove
Move
-
Cancle Edit
I would bind the menu to a Collection, and have the different UserControls alter the Collection when loaded.
EDIT - Here's an example
Your main View would contain something like this
<Menu ItemsSource="{Binding Path=CurrentUserControl.MenuItems}">
<Menu.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding MenuItemText}" />
<Setter Property="Command" Value="{Binding MenuItemCommand}" />
<Setter Property="CommandParameter" Value="{Binding MenuItemCommandParameter}" />
</Style>
</Menu.Resources>
</Menu>
While each UserControl would contain a Collection property of the MenuItems you would like to display
public class MenuItem
{
public string MenuItemText {get; set;}
public ICommand MenuItemCommand {get; set;}
public object MenuItemCommandParameter {get; set;}
}
...
public ObservableCollection<MenuItem> MenuItems;
You can use the CompositeCollection to merge multiple collection into one. Following the example from 1:
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<Grid Background="Transparent">
<Grid.Resources>
<x:Array Type="{x:Type sys:Object}" x:Key="extensions">
<Separator />
<MenuItem Header="Extension MenuItem 1" />
<MenuItem Header="Extension MenuItem 2" />
<MenuItem Header="Extension MenuItem 3" />
</x:Array>
</Grid.Resources>
<Grid.ContextMenu>
<ContextMenu>
<ContextMenu.ItemsSource>
<CompositeCollection>
<MenuItem Header="Standard MenuItem 1" />
<MenuItem Header="Standard MenuItem 2" />
<MenuItem Header="Standard MenuItem 3" />
<CollectionContainer Collection="{StaticResource extensions}" />
</CompositeCollection>
</ContextMenu.ItemsSource>
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</Window>
I did found a solution: http://www.codeproject.com/KB/menus/WPFMergeMenu.aspx But there should be something better
How about binding the visibility of certain menu options to booleans in the ViewModel, and using an IValueConverter to switch between Visible and Collapsed?
A simple approach is to build a series of if-then constructs in your code behind, to change the visibility of various menu items, depending on what user controls are visible.
精彩评论