Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ContextMenu in MVVM

I want to bind a contextmenu to a list of commands.

<Grid.ContextMenu>
    <ContextMenu ItemsSource="{Binding ItemContextCommands, Converter={StaticResource commandToStringConverter}}">
            <ContextMenu.ItemTemplate >
                    <DataTemplate DataType="MenuItem">
                            <MenuItem Command="{Binding}"></MenuItem>
                        </DataTemplate>
                </ContextMenu.ItemTemplate>
        </ContextMenu>
</Grid.ContextMenu>

The commandToStringConverter simply converts a list of commands to a list of strings calling the ToString() on each command in the list.

How can I achieve that the Command in each MenuItem is called?

like image 581
Mare Infinitus Avatar asked Mar 22 '13 09:03

Mare Infinitus


2 Answers

I would use a small "view model" to hold the informations for such a command.

class ContextAction : INotifyPropertyChanged
{
    public string Name;
    public ICommand Action;
    public Brush Icon;
}

make a collection inside your view model which should get the context actions like

ObservableCollection<ContextAction> Actions {get;set;}

and simply bind this collection to your ContextMenu.

<Grid.ContextMenu>
    <ContextMenu ItemsSource="{Binding Actions}" />

The ItemTemplate for the contextmenu items can now access the name, the command and whatever else you might need. It might be useful to change the CommandParameter as well so that it will call the command with the actions owning element, not with the action itself.

like image 83
dowhilefor Avatar answered Oct 02 '22 19:10

dowhilefor


An improved XAML version of @blindmils solution below:

<ContextMenu ItemsSource="{Binding MyCommandList}">
    <ContextMenu.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Setter Property="Header" Value="{Binding Displayname}" />
            <Setter Property="Command" Value="{Binding MyContextMenuCommand }" />
        </Style>
    </ContextMenu.ItemContainerStyle>
</ContextMenu>
like image 37
Ole K Avatar answered Oct 02 '22 20:10

Ole K