以编程方式禁用/启用WPF上下文菜单项

时间:2014-04-15 08:17:41

标签: .net wpf contextmenu

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”。

如何解决?

1 个答案:

答案 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