views:

148

answers:

1

I've got an issue with a custom control that I've written not firing it's ContextMenuOpening event when I hook it up programatically. The control is basically a wrapper for the standard TextBox:

public class MyTextBox : TextBox
{
    public MyTextBox()
    {
        this.ContextMenuOpening += new ContextMenuEventHandler(MyTextBox_ContextMenuOpening);
    }

    void MyTextBox_ContextMenuOpening(object sender, ContextMenuEventArgs e)
    {
        MessageBox.Show("ContextMenuOpening event fired");
    }
}

There's nothing suspect either about the XAML:

<local:MyTextBox Height="25" Width="300"/>

For some reason though, I can never get the event to fire. I'm trying to intercept the context menu so I can alter it (it's context sensitive) and really am trying to avoid having to hook up the event everywhere the control is used - surely this is possible?

A: 

Turns out you need to explicity set the ContextMenu to null when creating the object:

public MyTextBox()
{
    this.ContextMenu = null;
    this.Initialized += (s, e) =>
        ContextMenuOpening += new ContextMenuEventHandler(MyTextBox_ContextMenuOpening);
}

Then it works a treat :)

Tom Allen