当ContextMenu
中有MenuItem
时,如何以编程方式修改特定的ContextMenu
Separator
?
在父控件中我有
ContextMenuOpening="ModifyItems"
ContextMenu
是
<ContextMenu >
<MenuItem Header="Item1" Tag="SomeTag" />
<Separator />
<MenuItem Header="Item2" />
</ContextMenu>
我处理ContextMenuOpening
(根据Microsoft示例)
Private Sub ModifyItems(ByVal sender As System.Object, ByVal e As System.Windows.Controls.ContextMenuEventArgs)
Dim fe As FrameworkElement = TryCast(e.Source, FrameworkElement)
Dim cm As ContextMenu = fe.ContextMenu
For Each mi As MenuItem In cm.Items
If CType(mi.Tag, String) = "SomeTag" Then
mi.IsEnabled = IsEnabled()
End If
Next mi
End Sub
我遇到异常:
无法将“System.Windows.Controls.Separator”类型的对象强制转换为“System.Windows.Controls.MenuItem”。
如何解决?
答案 0 :(得分:1)
您需要检查该项目是否为MenuItem
:
For Each i In cm.Items
If TypeOf i Is MenuItem Then
Dim mi = CType(i, MenuItem)
If CType(mi.Tag, String) = "SomeTag" Then
mi.IsEnabled = IsEnabled()
End If
End If
Next mi