1

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

1 Answer 1

4
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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.