Erez
Erez

Reputation: 6446

wpf - commands , contextmenu

How can I put the ContextMenu in a resource xaml file and bind it's commands to my current window's commands ?

Upvotes: 1

Views: 1763

Answers (1)

Michal Ciechan
Michal Ciechan

Reputation: 13898

Command="{Binding SomeCommand}"

It will use your current controls DataContext which should hold a command property "SomeCommand"

E.G.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ContextMenu x:Key="SomeContextMenu">
        <MenuItem Header="Test Item" Command="{Binding TestCommand}" />
    </ContextMenu>
</ResourceDictionary>

And in my ViewModel I would have the following property

    public ICommand TestCommand { get; set; }

And in my View.xaml

<Button ContextMenu="{StaticResource SomeContextMenu}">Test Button</Button>

Therefore the buttons DataContext is my ViewModel, therefore the SomeContextMenu which is in a ResourceDictionary in a external file binds to the same DataContext as the button, and therefore finds the SomeCommand within the ViewModel.

Upvotes: 4

Related Questions