如何将具有 Command 的 ContextMenu 绑定到附加的 属性?

How to bind ContextMenu that has Command to the attached property?

我有一个名为 DockSite 的外部控件。 从 DockSite 控件显示 ContextMenu 时,将调用 MenuOpening 事件处理程序。

我想在调用 MenuOpening 事件时将我的 ContextMenu 添加到默认的 ContextMenu,并且我创建了如下附加的 属性 以扩展 DockSite 的行为。

    public static ContextMenu GetAddDocumentMenu(DependencyObject obj)
    {
        return (ContextMenu)obj.GetValue(AddDocumentMenuProperty);
    }

    public static void SetAddDocumentMenu(DependencyObject obj, ContextMenu value)
    {
        obj.SetValue(AddDocumentMenuProperty, value);
    }

    // Using a DependencyProperty as the backing store for AddDocumentMenu.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty AddDocumentMenuProperty =
        DependencyProperty.RegisterAttached("AddDocumentMenu", typeof(ContextMenu), typeof(DockSiteHook), new PropertyMetadata(new ContextMenu(), OnDocumentMenuChanged));

    private static void OnDocumentMenuChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var dockSite = (sender as DockSite);
        if (dockSite == null) return;

        ContextMenu on = (ContextMenu)e.NewValue;
        if (on is null) dockSite.MenuOpening -= DockSite_MenuOpening;
        else dockSite.MenuOpening += DockSite_MenuOpening;
    }

    private static void DockSite_MenuOpening(object sender, DockingMenuEventArgs e)
    {
        e.Menu.Items.Add(DockSiteHook.GetAddDocumentMenu(sender as DockSite));
    }

我在主窗口中使用了上面的代码,如下所示。

<docking:DockSite Grid.Row="1" x:Name="dockSite">

    <ap:DockSiteHook.AddDocumentMenu>
        <ContextMenu>
            <MenuItem Command="{Binding TestCommand}"/>
        </ContextMenu>
    </ap:DockSiteHook.AddDocumentMenu>

<docking:DockSite/>

但是 Visual Studio 抛出如下图所示的错误。

错误信息是"It can't bind the default value for AddDocumentMenu to the specific thread"。

我想将上下文菜单绑定到特定的附件 属性。

有人能告诉我为什么会出现上述错误吗?以及如何解决这个问题?

感谢阅读。

将默认值设置为null(或default(ContextMenu)):

public static readonly DependencyProperty AddDocumentMenuProperty = 
    DependencyProperty.RegisterAttached("AddDocumentMenu", typeof(ContextMenu), 
        typeof(DockSiteHook), new PropertyMetadata(null, OnDocumentMenuChanged));