What's wrong with this binding?

2019-03-04 12:34发布

问题:

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

回答1:

ContextMenus are not part of the same VisualTree as the rest of the UI, so your RelativeSource binding is not finding the ListBox

You can find the UI object the ContextMenu is attached to by using the PlacementTarget property of the ContextMenu

<Style x:Key="ContextMenuStyle" TargetType="telerik:RadMenuItem">
    <Setter Property="DataContext" Value="{Binding PlacementTarget.DataContext, 
        RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type telerik:RadContextMenu}}}" />
</Style>