3

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>

I get this (runtime) error for each element that uses the HierarchicalDataTemplate:

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')

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

Matthew
  • 28,056
  • 26
  • 104
  • 170

1 Answers1

17

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.

Try binding the DataContext via the PlacementTarget:

 DataContext="{Binding PlacementTarget.DataContext,
                       RelativeSource={RelativeSource Self}}"
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Ah, that makes sense. I ended up solving the problem by in-lining the context menu, since it was only one MenuItem and only used in one place, but your solution works too. – Matthew Aug 02 '11 at 16:37