What's wrong with this binding?

孤人 提交于 2019-12-31 04:36:07

问题


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>


来源:https://stackoverflow.com/questions/11202021/whats-wrong-with-this-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!