Question

I have an event in my MainWindow that is being fired from one of my child controls as a routed event. The MainWindow has an AddHandler call to catch the routed fire.

I would like to fire this same event from ANOTHER child element, but this element (a menuItem) gets created on the fly so when I try to use AddHandler in MainWindow, like:

 this.AddHandler(MyMenuItem.EditExtensionsEvent, new RoutedEventHandler(this.EditExtensions));

I get a null argument exception because MyMenuItem does not exist yet.

Anyone know of a way that I can still use a routed event?

Was it helpful?

Solution

I assume your MyMenuItem is either not in the namespace of your application or the EditExtensionsEvent isn't a static RoutedEvent of the class MyMenuItem.

It should look something like this:

public class MyMenuItem
{
public static readonly RoutedEvent EditExtensionsEvent
..
}

see http://msdn.microsoft.com/en-us/library/ms752288.aspx

If it is declared this way it should work as you've shown here

EDIT: I'd suggest registering with an already existing event to make sure your EditExtensionsEvent is working properly.

public MainWindow()
{
  ..
  this.AddHandler(MenuItem.ClickEvent, new RoutedEventHandler(this.MenuItemClick));
}

private void MenuItemClick(object sender, RoutedEventArgs e)
{
   MessageBox.Show("Clicked");
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top