0

Imagine situation, where I have user control containing button:

<UserControl>
  <Button Click="ShowContextMenu" />
</UserControl>

This button will on the click event display ContextMenu:

ContextMenu contextMenu = this.FindResource("ContextMenuDefinition") as ContextMenu;
contextMenu.PlacementTarget = sender as Button;
contextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Top;
contextMenu.IsOpen = true;

Defined as Resource in the ResourceDictionary (separate file):

<ContextMenu x:Key="ContextMenuDefinition" DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
    <ContextMenu.Template>
        <ControlTemplate>
            <Button Style="{StaticResource MyStyle}" Command="{Binding AwesomeCommand}"  />
        </ControlTemplate>
    </ContextMenu.Template>
</ContextMenu>

How can I trigger any AwesomeCommand from this context menu? - how and where should I define it and then pass it to the context menu for invocation?

Many thanks!

user969153
  • 568
  • 8
  • 25

1 Answers1

0

The AwesomeCommand must reside in the ViewModel. This View should set as DataContext for the UserControl. The UserControl will have the button and ContextMenu. The ContextMenu should declared in the following way.

ViewModel

public class ViewModel
{
    public DelegateCommand AwesomeCommand { get; set; }
}

XAML

    <Button>
        <Button.ContextMenu>
            <ContextMenu>
                <MenuItem Command="{Binding AwesomeCommand}" />
            </ContextMenu>
        </Button.ContextMenu>
    </Button>

I understand why you have a Click handler to open context menu. To open context menu on left click, follow this approach.

WPF Context menu on left click

Community
  • 1
  • 1
Jawahar
  • 4,775
  • 1
  • 24
  • 47
  • This does not help at all. How to use viewmodel if it's defined in style resources? And I don't have standard MenuItem(s), but custom template with button. – user969153 Nov 26 '14 at 19:49