dotnet / dotnet/wpf

Opening a ContextMenu programmatically doesn't trigger the ContextMenuOpening event

Open
#8,879 2 comments 1 reaction 0 assignees View on GitHub
Documentation
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

- TargetFramework: net8.0-windows
- OS: Windows 11 Enterprise, x64
- Also reproducible on .NET Framework 4.8

# Problem Description

When a `ContextMenu` is opened programmatically by setting the `IsOpen` property to `true`, the `OnContextMenuOpening` handler is never called.

# Minimal repro

XAML:
```xaml






```

Code-behind
```cs
using System.Windows;
using System.Windows.Controls;

namespace WpfApp1
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

protected override void OnContextMenuOpening(ContextMenuEventArgs e)
{
base.OnContextMenuOpening(e);
}

private void Button_Click(object sender, RoutedEventArgs e)
{
ctxMenu.IsOpen = true;
}
}
}
```

Clicking the button opens up the `ContextMenu` of the Window programmatically. Notice that the `OnContextMenuOpening` handler is never called.

# Expected behavior

The ContextMenu opens and the `OnContextMenuOpening` is called the same way it works when right-clicking to open it.

# Actual behavior

The ContextMenu opens but the `OnContextMenuOpening` method is never called.

# Regression?

I also tested on a project with the `.NET Framework 4.8` Target Framework and the issue is still reproducible.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.