0

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?

joepetrakovich
  • 1,344
  • 3
  • 24
  • 42

1 Answers1

1

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");
}
SvenG
  • 5,155
  • 2
  • 27
  • 36
  • This fixed the null argument exception, but for some reason my event is not being fired from the parent. I'm not sure where to go from here. – joepetrakovich Dec 21 '11 at 20:21
  • Is it possible that since my menuItem is being created on the fly, that MainWindow is not registered as its parent so the bubbled event is not making it? – joepetrakovich Dec 21 '11 at 20:30
  • If your MenuItem is part of the VisualTree everything's fine and it doens'nt matter if it was created during design time or runtime. I've edited my post above and hope this one helps ... – SvenG Dec 22 '11 at 08:07