为什么我不能用的DataContext = {}绑定为我的上下文菜单?我不、上下文、为我、能用

2023-09-03 01:38:23 作者:银河失声

我有code,它看起来是这样的:

I have code that looks something like this:

<HierarchicalDataTemplate
    DataType="{x:Type local:SomeType}"
    ItemsSource="{Binding SomeOtherItems}"
    >
    <DockPanel Margin="4">
        <DockPanel.ContextMenu>
            <local:SomeContextMenu DataContext="{Binding}" />
        </DockPanel.ContextMenu>
        <CheckBox IsChecked="{Binding SomeBooleanProperty, Mode=TwoWay}" />
        <TextBlock
            Margin="4,0"
            Text="{Binding Name}" />
    </DockPanel>
</HierarchicalDataTemplate>

如果没有上下文菜单,一切都按预期工作。但是,当我加入这一行:

Without the context menu, everything works as expected. But when I add these lines:

<DockPanel.ContextMenu>
    <local:SomeContextMenu DataContext="{Binding}" />
</DockPanel.ContextMenu>

我得到这个(运行时)错误的每个元素使用 HierarchicalDataTemplate

System.Windows.Data错误:3:找不到元素提供的DataContext。 BindingEx pression:(无路径); DataItem的= NULL;目标元素是'SomeContextMenu'(名称='');目标属性的DataContext(类型'对象')

System.Windows.Data Error: 3 : Cannot find element that provides DataContext. BindingExpression:(no path); DataItem=null; target element is 'SomeContextMenu' (Name=''); target property is 'DataContext' (type 'Object')

为什么在绑定 S表示一切工作,除非上下文菜单,而不是上下文菜单?

Why do the Bindings work for everything except the context menu, but not for the context menu?

推荐答案

首先,的DataContext ={结合}并没有太大的意义,因为这将结合在DataContext到DataContext。这里的问题也许在于文本菜单是不是在逻辑树,它的可视树断开,因为ContextMenus是浮动的弹出窗口。

First of all, DataContext="{Binding}" does not make much sense as that would bind the DataContext to the DataContext. The problem here is probably that the ContextMenu is not in the logical tree, and its visual tree is disconnected since ContextMenus are floating popups.

尝试通过PlacementTarget绑定的DataContext:

Try binding the DataContext via the PlacementTarget:

 DataContext="{Binding PlacementTarget.DataContext,
                       RelativeSource={RelativeSource Self}}"