The problem

When using WPF OnContextMenuOpening, ContextMenu doesn’t display on first load.

The reason

The OnContextMenuOpening routed event is used for dynamically creating a ContextMenu object for a particular UIElement.

Each UIElement has a ContextMenu property which dictates what gets displayed when a user right-clicks on it. If the property is null, nothing will be displayed. If the property is not null, the context menu that it references will be displayed.

The catch? The ContextMenu property must not be null before the event handler first fires, or the menu won’t load. This appears to be a WPF bug.

The solution

Create an empty ContextMenu object and assign it to each UIElement that’s going to have any context menu displayed. In the OnContextMenuOpening event, either Clear() the existing context menu or just create a new one and assign the property to the object reference. Either will work.