如何以编程方式打开上下文菜单时引发ContextMenuOpening事件

时间:2014-06-06 14:06:30

标签: c# wpf wpf-controls contextmenu

当我打开带有<control>.ContextMenu.IsOpen = true的上下文菜单时,上下文菜单变得可见,但是没有触发打开或关闭事件。

当我以编程方式打开上下文菜单时,如何确保引发ContextMenuOpeningContextMenuClosing事件?


演示:

查看以下XAML

<Button Name="ContextMenuButton" 
        Content="Click me!" 
        Click="ContextMenuButton_Click" 
        ContextMenuOpening="ContextMenuButton_OnContextMenuOpening"
        ContextMenuClosing="ContextMenuButton_OnContextMenuClosing">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Header="First element" />
            <MenuItem Header="Second element" />
        </ContextMenu>
    </Button.ContextMenu>
</Button>

以下代码隐藏

public MainWindow() // Constructor
{
    InitializeComponent();
    ContextMenuButton.ContextMenuOpening += (sender, args) => Debug.Print("Opening #2");
    ContextMenuButton.ContextMenuClosing += (sender, args) => Debug.Print("Closing #2");
}

private void ContextMenuButton_Click(object sender, RoutedEventArgs e)
{
    Button button = (sender as Button);
    button.ContextMenu.IsOpen = true; // How should I open the ContextMenu?
}

private void ContextMenuButton_OnContextMenuOpening(object sender, ContextMenuEventArgs e)
{
    Debug.Print("Opening #1");
}

private void ContextMenuButton_OnContextMenuClosing(object sender, ContextMenuEventArgs e)
{
    Debug.Print("Closing #1");
}

右键单击按钮时的行为:

上下文菜单正在打开。

输出是:

Opening #1
Opening #2
Closing #1
Closing #2

左键单击按钮时的行为:

上下文菜单正在打开。

输出是:

<Nothing>

2 个答案:

答案 0 :(得分:4)

问题是您已经在Button的ContextMenuOpening上附加了事件,并且由于您手动调用ContextMenu,因此事件无法触发

所以要让事件附加来自ContextMenu的Opened和Closed事件

    public MainWindow() // Constructor
    {
        InitializeComponent();
        ContextMenuButton.ContextMenu.Opened += (sender, args) => Debug.Print("Opening #2");
        ContextMenuButton.ContextMenu.Closed += (sender, args) => Debug.Print("Closing #2");
    }

XAML

    <Button Name="ContextMenuButton" 
            Content="Click me!" 
            Click="ContextMenuButton_Click" >
        <Button.ContextMenu>
            <ContextMenu Opened="ContextMenuButton_OnContextMenuOpening" Closed="ContextMenuButton_OnContextMenuClosing">
                <MenuItem Header="First element" />
                <MenuItem Header="Second element" />
            </ContextMenu>
        </Button.ContextMenu>
    </Button>

事件,ContextMenuEventArgs更改为RoutedEventArgs

    private void ContextMenuButton_OnContextMenuOpening(object sender, RoutedEventArgs e)
    {
        Debug.Print("Opening #1");
    }

    private void ContextMenuButton_OnContextMenuClosing(object sender, RoutedEventArgs e)
    {
        Debug.Print("Closing #1");
    }

按钮单击保持不变。

这应该可以解决您的问题

答案 1 :(得分:0)

打开事件和打开事件之间有区别。通常,Opening事件用于在显示菜单之前动态地构建菜单。在这种情况下,上述解决方案将无效。

U 1