WPF Custom TextBox ContextMenuOpening Problem
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 开发者_JS百科really am trying to avoid having to hook up the event everywhere the control is used - surely this is possible?
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 :)
The ContextMenuOpening-Event will only be fired after you assign a new context menu to the property ContextMenu:
public MyTextBox()
{
this.ContextMenu = new ContextMenu();
this.ContextMenu.Items.Add(new MenuItem {Header = "Do stuff"});
...
}
精彩评论