wpf - 命令,contextmenu

时间:2010-10-25 12:24:46

标签: wpf contextmenu command

如何将ContextMenu放在资源xaml文件中并将其命令绑定到当前窗口的命令?

1 个答案:

答案 0 :(得分:4)

Command="{Binding SomeCommand}"

它将使用您当前的控件DataContext,它应该包含命令属性“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>

在我的ViewModel中,我将拥有以下属性

    public ICommand TestCommand { get; set; }

在我的View.xaml

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

因此DataContext按钮是我的ViewModel,因此外部文件中ResourceDictionary中的SomeContextMenu与按钮绑定到相同的DataContext,因此在ViewModel中找到SomeCommand。