我正在尝试访问ContextMenu中的MenuItem,而ContextMenu本身是一个协会资源的一部分
<TreeView.Resources>
<ContextMenu x:Key ="GroupContext" StaysOpen="true">
<MenuItem Header="Blast to Whole Group" Click="BlastGroup_Click"/>
</ContextMenu>
<ContextMenu x:Key ="ContactContext" Style="{x:Null}" Loaded="ContextMenu_Loaded">
<MenuItem Header="Delete Contact" Click ="ContactDelete_Click"/>
<MenuItem x:Name="ModifyGroupMenuItem" Header="Modify Grouping" Style="{x:Null}">
</MenuItem>
</ContextMenu>
</TreeView.Resources>
如何获得ModifyGroupMenuItem? 我找到了一个解决方案来获取ContextMenu WPF control reference from xaml is not visible on the code side
答案 0 :(得分:6)
通过Items集合的索引,或通过浏览逻辑树。
ContextMenu menu = this.Resources["ContactContext"] as ContextMenu;
MenuItem menuitemindex0 = menu.Items[0] as MenuItem;
MenuItem menuitemindex1 = menu.Items[1] as MenuItem;
MenuItem menuitembyname = LogicalTreeHelper.FindLogicalNode(menu, "ModifyGroupMenuItem") as MenuItem;