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 Binding
s work for everything except the context menu, but not for the context menu?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…