Reputation: 2813
How to modify a specific ContextMenu
MenuItem
programmatically when the ContextMenu
has a Separator
in it?
In the parent control I have
ContextMenuOpening="ModifyItems"
The ContextMenu
is
<ContextMenu >
<MenuItem Header="Item1" Tag="SomeTag" />
<Separator />
<MenuItem Header="Item2" />
</ContextMenu>
I handle the ContextMenuOpening
(according to Microsoft example)
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
I run into exception:
Unable to cast object of type 'System.Windows.Controls.Separator' to type 'System.Windows.Controls.MenuItem'.
How to resolve that?
Upvotes: 1
Views: 2372
Reputation: 32587
You need to check if the item is a 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
Upvotes: 3