I'm trying to assign DataContext to a MenuItem, which is part of ListBox.
<Style x:Key="ContextMenuStyle" TargetType="telerik:RadMenuItem">
<Setter Property="DataContext" Value="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=telerik:RadListBox}, Path=DataContext}" />
</Style>
<DataTemplate x:Key="TemplateSelector">
<ContentPresenter Content="{Binding}" Name="contentPresenter">
<telerik:RadContextMenu.ContextMenu>
<telerik:RadContextMenu>
<telerik:RadMenuItem Header="Connect" Click="RadMenuItem_Click" Style="{StaticResource ResourceKey=ContextMenuStyle}" />
<telerik:RadMenuItem Header="Disconnect" />
<telerik:RadMenuItem Header="Delete Database" />
</telerik:RadContextMenu>
</telerik:RadContextMenu.ContextMenu>
</ContentPresenter>
</DataTemplate>
<Grid>
<telerik:RadListBox x:Name="lsbDevices" ItemsSource="{Binding Path=Devices}" ItemTemplate="{StaticResource TemplateSelector}"
SelectedItem="{Binding SelectedDevice, Mode=TwoWay}" Grid.Row="0" />
</Grid>
Here's what I do. RadListBox's DataContext is set to my ViewModel. I want to assign this ViewModel to every RadMenuItem's DataContext through ContextMenuStyle, but it's not working. RadListBox's DataContext is properly set to my modelview, but RadMenuItem's datacontext is null. What am I missing?
Thanks
ContextMenus
are not part of the sameVisualTree
as the rest of the UI, so yourRelativeSource
binding is not finding theListBox
You can find the UI object the
ContextMenu
is attached to by using thePlacementTarget
property of theContextMenu