Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
195 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...