WPF ContextMenu Dictionary <Key, List <Value> data binding

Assume the following class definitions.

public enum ContentType { Playlist, Audio, Video, Picture } public interface IDataProvider { string Name { get; } } public class ProviderList : List<IDataProvider> { } public class MainViewModel { public Dictionary<ContentType, ProviderList> ProvidersDictionary; public MainViewModel() { if (IsInDesignMode) { // Code runs in Blend --> create design time data. } else { // Code runs "for real" this.ProvidersDictionary = new Dictionary<ContentType, ProviderList>(); ProviderList providerList = new ProviderList(); providerList.Add(new DataProvider()); this.ProvidersDictionary.Add(ContentType.Audio, providerList); providerList = new ProviderList(providerList); providerList.Add(new DataProvider()); this.ProvidersDictionary.Add(ContentType.Video, providerList); } } } 

So, this ProvidersDictionary property is bound to the Window context menu as follows:

 <Window.ContextMenu> <ContextMenu ItemsSource="{Binding ProvidersDictionary}"> <ContextMenu.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Value}"> <TextBlock Margin="1" Text="{Binding Key}" Height="20"/> <HierarchicalDataTemplate.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Name}" /> </DataTemplate> </HierarchicalDataTemplate.ItemTemplate> </HierarchicalDataTemplate> </ContextMenu.ItemTemplate> </ContextMenu> </Window.ContextMenu> 

The question arises: how to make ICommand data binding for the DataProvider menu item and get the data type (enumeration type) and data provider (IDataProvider interface) in the Run Method command.

Update I want some command class to bind to MenuItems, for example:

 class DataProviderMenuSelectCommand : ICommand { #region ICommand Members public void Execute(object parameter) { ContentTypeProviderPair contentProviderPair = parameter as ContentTypeProviderPair; if (contentProviderPair != null) { // contentProviderPair.Type property - ContentType // contentProviderPair.Provider property - IProvider } } } 

MainViewModel will expose an instance of this command class as a property.

+4
source share
1 answer

Problem resolved:

 <UserControl x:Class="DataProvidersView" ... <ContextMenu.ItemContainerStyle> <Style TargetType="{x:Type MenuItem}"> <Setter Property="Command" Value="{Binding Path=DataContext.DataProviderSwitchCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type vw:DataProvidersView}}}" /> <Setter Property="CommandParameter"> <Setter.Value> <MultiBinding> <Binding Path="DataContext.Key" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}" /> <Binding /> </MultiBinding> </Setter.Value> </Setter> </Style> </ContextMenu.ItemContainerStyle> </UserControl> 
0
source

All Articles