菜单项打开和关闭事件

时间:2010-02-18 08:55:21

标签: c# wpf event-handling wpf-controls menuitem

每当菜单项的子菜单打开时,我想处理一个事件。关闭也是如此。我怎么能这样做?

3 个答案:

答案 0 :(得分:13)

很简单。订阅MenuItem的{​​{1}}活动。传统方式:

SubmenuOpened

或酷动态方法:

MidItem.SubmenuOpened += new RoutedEventHandler(MidItem_SubmenuOpened);

private void MidItem_SubmenuOpened(object sender, RoutedEventArgs e)
{
    //Menu Open Logic Here
}

答案 1 :(得分:1)

不确定您想要什么,但请查看ContextMenuMenuItem的这些活动:

ContextMenu

http://msdn.microsoft.com/en-us/library/system.windows.controls.contextmenu_events.aspx

MenuItem

http://msdn.microsoft.com/en-us/library/system.windows.controls.menuitem_events.aspx

我认为ContextMenuOpeningContextMenuClosing可能很有趣;)

答案 2 :(得分:0)

如果您希望在真正的开业之前开业,可以将菜单项子类化

Imports System.ComponentModel
Public Class CustomMenuItem
    Inherits MenuItem

    Public Event SubMenuOpening(sender As Object, e As CancelEventArgs)
    Public Event SubMenuClosing(sender As Object, e As CancelEventArgs)
    Protected Overrides Sub OnPropertyChanged(e As DependencyPropertyChangedEventArgs)
        If e.Property Is MenuItem.IsSubmenuOpenProperty Then
            Dim MyCancelEventArgs As New CancelEventArgs
            If e.NewValue Then
                RaiseEvent SubMenuOpening(Me, MyCancelEventArgs)
                If MyCancelEventArgs.Cancel Then Me.IsSubmenuOpen = False
            Else
                RaiseEvent SubMenuClosing(Me, MyCancelEventArgs)
                If MyCancelEventArgs.Cancel Then Me.IsSubmenuOpen = True
            End If
        End If
        MyBase.OnPropertyChanged(e)
    End Sub

End Class

我知道这是VB,但是很容易转换。 另外,使用CancelEventArgs,您可以模拟取消打开(或关闭)操作。