上下文菜单下的菜单项没有被绑定到ViewModel

本文关键字:绑定 ViewModel 菜单 菜单项 上下文 | 更新日期: 2023-09-27 18:10:45

我有两个菜单项,我把它们作为一个菜单项的上下文菜单的一部分。我能够绑定父菜单项的DataContext,但不知何故,我不能将子菜单项与父菜单项的DataContext绑定。以下是代码片段:

    <MenuItem Name="miCommunityHealthIssues" Margin="3,3,3,6" Click="miCommunityHealthIssues_Click" DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" Style="{StaticResource ShowMenuItemFilterStyle}">
                        <MenuItem.ContextMenu>
                            <ContextMenu DataContext="{Binding RelativeSource={RelativeSource Self}, Path=PlacementTarget.DataContext}"> 
                                <MenuItem Name="miShowComhealthIssues" IsCheckable="True" IsChecked="{Binding IncludeCommunityRecords}" Checked="MenuItem_Checked" Unchecked="MenuItem_Unchecked"/>
                                <MenuItem Name="miShowSupComhealthIssues" IsCheckable="True" IsChecked="{Binding IncludeSuppressedCommunityRecords}" Checked="miShowSupComhealthIssues_Checked" Unchecked="miShowSupComhealthIssues_Unchecked"/>                                    
                            </ContextMenu>
                        </MenuItem.ContextMenu>
                    </MenuItem>

请帮助我的代码片段,而不是引导我到另一个链接。我已经参考了很多链接,但无法找到解决方案。

上下文菜单下的菜单项没有被绑定到ViewModel

我怀疑部分问题是在ContextMenuDataContext。当我尝试重新创建您的代码时,我无法在绑定中指定Path=PlacementTarget.DataContext

如果你只是想引用父MenuItemDataContext,我建议定义ContextMenuDataContext。父元素MenuItemDataContext将应用于所有子元素,包括子元素MenuItem:

<MenuItem Name="miCommunityHealthIssues" Margin="3,3,3,6" Click="miCommunityHealthIssues_Click" DataContext="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}" Style="{StaticResource ShowMenuItemFilterStyle}">
    <MenuItem.ContextMenu>
        <!-- no datacontext definition necessary -->
        <ContextMenu> 
            <MenuItem Name="miShowComhealthIssues" IsCheckable="True" IsChecked="{Binding IncludeCommunityRecords}" Checked="MenuItem_Checked" Unchecked="MenuItem_Unchecked"/>
            <MenuItem Name="miShowSupComhealthIssues" IsCheckable="True" IsChecked="{Binding IncludeSuppressedCommunityRecords}" Checked="miShowSupComhealthIssues_Checked" Unchecked="miShowSupComhealthIssues_Unchecked"/>
        </ContextMenu>
    </MenuItem.ContextMenu>
</MenuItem>