2009-09-03 56 views
1

當我嘗試獲取WPF「矩形」的事件信息時,如果routedEvent是該對象的本機事件(例如'MouseDown'),它將起作用(例如,賦值僅作爲示例) 。GetEvent()爲附加事件返回null

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

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

但是,當我想要得到的EventInfo一個附加事件(我想我正確地使用這個詞)上,如矩形:

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

GetEvent()返回null

關於如何獲取附加事件的事件信息的任何想法。

感謝

回答

3

您可能需要使用更具體的EventManager.GetRoutedEventsForOwner方法。

我相信MSDN文檔是不正確的,當他們說:

基類都包含在 搜索。

這裏的證明:

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); 

因此,您可能需要自己抓取類型層次,或者如果它是一個一次性只是通過在typeof(FrameworkElement)代替或typeof(Rectangle)

+1

RoutedEvent [] routedEvents = EventManager.GetRoutedEventsForOwner(d.GetType());返回null? 我驗證了d.GetType()返回矩形。 – 2009-09-03 15:55:56

+0

更新了我的答案。 – 2009-09-03 16:17:59

+1

肯特,感謝您的建議。我感覺我正在接近。 我原來的要求是獲取EventInfo對象,因爲我想添加一個事件處理程序(通過.AddEventHandler)。如果我得到一個RoutedEvent類型而不是EventInfo(通過您的推薦),我該如何添加一個處理程序?謝謝 – 2009-09-03 19:28:56

0

因爲附加事件沒有公開爲常規的C#事件。在Mouse類,有沒有這樣的:

public event MouseButtonEventHandler MouseDown; 

取而代之的是RoutedEvent類型的靜態字段MouseDownEvent

public static readonly RoutedEvent MouseDownEvent; 

您使用EventManager訂閱/退訂事件。