开发者

wpf - commands , contextmenu

开发者 https://www.devze.com 2023-01-21 16:04 出处:网络
How can I put the ContextMenu in a resource xaml file and bind it\'s commands to my cur开发者_开发问答rent window\'s commands ?Command=\"{Binding SomeCommand}\"

How can I put the ContextMenu in a resource xaml file and bind it's commands to my cur开发者_开发问答rent window's commands ?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消