本文介绍了为什么我不能用的DataContext = {}绑定为我的上下文菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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(类型'对象')

为什么在绑定 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}}"

这篇关于为什么我不能用的DataContext = {}绑定为我的上下文菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 21:46