且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

WPF:将 ContextMenu 绑定到 MVVM 命令

更新时间:2022-05-11 17:59:13

问题是 ContextMenu 它不在可视化树中,所以你基本上要告诉 Context menu 使用哪个数据上下文.

The problem is that the ContextMenu it not in the visual tree, so you basically have to tell the Context menu about which data context to use.

查看 这篇博文 有一个非常好的 Thomas Levesque 解决方案.

Check out this blogpost with a very nice solution of Thomas Levesque.

他创建了一个继承 Freezable 的类 Proxy 并声明了一个 Data 依赖属性.

He creates a class Proxy that inherits Freezable and declares a Data dependency property.

public class BindingProxy : Freezable
{
    protected override Freezable CreateInstanceCore()
    {
        return new BindingProxy();
    }

    public object Data
    {
        get { return (object)GetValue(DataProperty); }
        set { SetValue(DataProperty, value); }
    }

    public static readonly DependencyProperty DataProperty =
        DependencyProperty.Register("Data", typeof(object), typeof(BindingProxy), new UIPropertyMetadata(null));
}

然后可以在 XAML 中声明它(在可视化树中已知正确 DataContext 的位置):

Then it can be declared in the XAML (on a place in the visual tree where the correct DataContext is known):

<Grid.Resources>
    <local:BindingProxy x:Key="Proxy" Data="{Binding}" />
</Grid.Resources>

并在可视化树外的上下文菜单中使用:

And used in the context menu outside the visual tree:

<ContextMenu>
    <MenuItem Header="Test" Command="{Binding Source={StaticResource Proxy}, Path=Data.MyCommand}"/>
</ContextMenu>