Click here to Skip to main content
14,923,040 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Situation: I have ColorPicker in Canvas.
Goal: To use events of ContextMenu.
Problem: The ContextMenuOpening event doesn't fire and the ContextMenu.Opened event results error as many other events.
1. I mean a drop menu by "ContextMenu", but i don't know what "ContextMenu" exactly is.
2. It is Extended WPF Toolkit and to use it you need to add extended dlls.
public partial class MainWindow : Window
    public MainWindow()

        canvas.Background = Brushes.Black;
        this.Content = canvas;

        ColorPicker colorpicker = new ColorPicker();
        colorpicker.ContextMenuOpening += delegate { System.Windows.MessageBox.Show("a"); }; // Doesn't fire.
        colorpicker.ContextMenu.Opened += delegate { System.Windows.MessageBox.Show("a"); }; // Error: Object reference not set to an instance of an object.

    Canvas canvas = new Canvas();
Updated 9-Oct-15 3:18am

1 solution

A context menu is the menu that appears when you right-click on something. The color-picker's popup isn't a context menu, which is why the ContextMenuOpening event doesn't fire. And unless you've explicitly set the ContextMenu property, it will return null, which is why you're getting a NullReferenceException when you try to subscribe to it's Opened event.

Looking at the source code[^] for the ColorPicker control, it doesn't seem to fire an event when the popup opens. Your best bet is probably to subscribe to the property change event for the IsOpen property:
DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(ColorPicker.IsOpenProperty, typeof(ColorPicker));
descriptor.AddValueChanged(colorpicker, delegate 
    if (colorpicker.IsOpen)
        // Do something here...
Ziya1995 9-Oct-15 10:38am
I got your idea, but the code you gave results 2 errors:

1. The best overloaded method match for 'System.ComponentModel.DependencyPropertyDescriptor.FromProperty(System.ComponentModel.PropertyDescriptor)' has some invalid arguments

2. Argument 1: cannot convert from 'System.Windows.DependencyProperty' to 'System.ComponentModel.PropertyDescriptor'
Richard Deeming 9-Oct-15 10:41am
Sorry - for some reason you need to pass the type as well as the property. I've updated the answer:
DependencyPropertyDescriptor.FromProperty(ColorPicker.IsOpenProperty, typeof(ColorPicker))

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900