views:

242

answers:

2

When I try to get the eventinfo of a WPF 'rectangle', if the routedEvent is a native event to the object (e.g. 'MouseDown') it works (assignments are for example only).

DependencyObject d = rectangle;
string routedEvent = "MouseDown";

EventInfo eventInfo = d.GetType().GetEvent(routedEvent, 
                BindingFlags.Public | BindingFlags.Instance);

But when I want to get the EventInfo for an attached event (I think I am using that term correctly) on the rectangle like:

string routedEvent = "Microsoft.Surface.Presentation.Contacts.ContactDownEvent";

GetEvent() returns null

Any idea on how to get the eventinfo for an attached event.

Thanks

Dan

+2  A: 

You may want to use the more specific EventManager.GetRoutedEventsForOwner method.

I believe the MSDN docs are incorrect when they say:

Base classes are included in the search.

Here's proof:

Debug.Assert(EventManager.GetRoutedEventsForOwner(typeof(Rectangle)) == null);
Debug.Assert(EventManager.GetRoutedEventsForOwner(typeof(Shape)) == null);
//even though FrameworkElement is a base class of the above!
Debug.Assert(EventManager.GetRoutedEventsForOwner(typeof(FrameworkElement)) != null);

Therefore, you may need to crawl the type hierarchy yourself, or if it's a one-off just pass in typeof(FrameworkElement) instead or typeof(Rectangle).

HTH, Kent

Kent Boogaart
RoutedEvent[] routedEvents = EventManager.GetRoutedEventsForOwner(d.GetType()); returns null?I verified d.GetType() returns rectangle.
Dan dot net
Updated my answer.
Kent Boogaart
Kent, thank for the advice. I feel like I am getting closer. My original request was to get the EventInfo object because I want to add an event handler (via .AddEventHandler). If I get a RoutedEvent type instead of EventInfo (via your recommendation), how do I add a handler? Thanks
Dan dot net
@DanI'm facing the same scenario as you. Did you find a solution to the EventInfo and RoutedEvent problem?
Tri Q
A: 

Because attached events are not exposed as regular C# events. In the Mouse class, there is nothing like that :

public event MouseButtonEventHandler MouseDown;

Instead, there is a static field MouseDownEvent of type RoutedEvent :

public static readonly RoutedEvent MouseDownEvent;

You use the EventManager to subscribe/unsubscribe to the event.

Thomas Levesque