RoutedEventHelper.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Windows;
  3. namespace Hardcodet.Wpf.TaskbarNotification
  4. {
  5. /// <summary>
  6. /// Helper class used by routed events of the
  7. /// <see cref="TaskbarIcon"/> class.
  8. /// </summary>
  9. internal static class RoutedEventHelper
  10. {
  11. #region RoutedEvent Helper Methods
  12. /// <summary>
  13. /// A static helper method to raise a routed event on a target UIElement or ContentElement.
  14. /// </summary>
  15. /// <param name="target">UIElement or ContentElement on which to raise the event</param>
  16. /// <param name="args">RoutedEventArgs to use when raising the event</param>
  17. internal static void RaiseEvent(DependencyObject target, RoutedEventArgs args)
  18. {
  19. var uiElement = target as UIElement;
  20. if (uiElement != null)
  21. {
  22. uiElement.RaiseEvent(args);
  23. }
  24. else
  25. {
  26. var contentElement = target as ContentElement;
  27. if (contentElement != null)
  28. {
  29. contentElement.RaiseEvent(args);
  30. }
  31. }
  32. }
  33. /// <summary>
  34. /// A static helper method that adds a handler for a routed event
  35. /// to a target UIElement or ContentElement.
  36. /// </summary>
  37. /// <param name="element">UIElement or ContentElement that listens to the event</param>
  38. /// <param name="routedEvent">Event that will be handled</param>
  39. /// <param name="handler">Event handler to be added</param>
  40. internal static void AddHandler(DependencyObject element, RoutedEvent routedEvent, Delegate handler)
  41. {
  42. var uie = element as UIElement;
  43. if (element != null && uie != null)
  44. {
  45. uie.AddHandler(routedEvent, handler);
  46. }
  47. else
  48. {
  49. var ce = element as ContentElement;
  50. if (element != null && ce != null)
  51. {
  52. ce.AddHandler(routedEvent, handler);
  53. }
  54. }
  55. }
  56. /// <summary>
  57. /// A static helper method that removes a handler for a routed event
  58. /// from a target UIElement or ContentElement.
  59. /// </summary>
  60. /// <param name="element">UIElement or ContentElement that listens to the event</param>
  61. /// <param name="routedEvent">Event that will no longer be handled</param>
  62. /// <param name="handler">Event handler to be removed</param>
  63. internal static void RemoveHandler(DependencyObject element, RoutedEvent routedEvent, Delegate handler)
  64. {
  65. var uie = element as UIElement;
  66. if (uie != null)
  67. {
  68. uie.RemoveHandler(routedEvent, handler);
  69. }
  70. else
  71. {
  72. var ce = element as ContentElement;
  73. if (ce != null)
  74. {
  75. ce.RemoveHandler(routedEvent, handler);
  76. }
  77. }
  78. }
  79. #endregion
  80. }
  81. }