I have a requirement to show a list of items in a context menu. In addition to this, I need to show the frequently used items (configurable by user) on the top, followed by a se开发者_如何学运维parator, and then the standard list of all the items. I know, I can add all the items to context menu at runtime but I want to explore different options too. The question is - is it possible to:
- Bind the standard list in xaml and then add the frequently used items at runtime. OR
- Bind the context menu to two separate list OR
- Any other better option
Please note that I need to maintain two separate lists due to some technical reasons. I am not showing any existing code because this question may be considered as a generic question and may apply to any control.
The second option is doable using a CompositeCollection
, however the binding capabilities are a bit dimished (cannot use DataContext
, ElementName
or RelativeSource
) in the CollectionContainer.Collection
-Binding.
This answer of mine on another question shows two ways in which you can bind. If you cannot make do with those restrictions you will have to create the composite collection in code-behind.
I would manage my menus in the ViewModels, not in the XAML. My ViewModel would be responsible for returning a collection that combines both the standard Menu collection, and the custom UserCollection.
Usually I separate the items with a null
value, and use a DataTrigger to draw the template as a Separator if the item is null.
Something like this:
myMenu.AddRange(UserMenu);
myMenu.Add(null);
myMenu.AddRange(StandardMenu);
and the XAML...
<ContextMenu ItemsSource="{Binding MyMenu}">
<ContextMenu.Resources>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Template"
Value="{StaticResource MyMenuItemTemplate}" />
<Style.Triggers>
<DataTrigger Binding="{Binding }" Value="{x:Null}">
<Setter Property="Template"
Value="{StaticResource MySeparatorTemplate}" />
</DataTrigger>
</Style.Resources>
</Style>
</ContextMenu.Resources>
</ContextMenu>
精彩评论