EventTriggerBase.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. using System;
  2. using System.ComponentModel;
  3. using System.Globalization;
  4. using System.Reflection;
  5. using System.Windows;
  6. namespace HandyControl.Interactivity;
  7. public abstract class EventTriggerBase : TriggerBase
  8. {
  9. public static readonly DependencyProperty SourceNameProperty = DependencyProperty.Register("SourceName",
  10. typeof(string), typeof(EventTriggerBase), new PropertyMetadata(OnSourceNameChanged));
  11. public static readonly DependencyProperty SourceObjectProperty = DependencyProperty.Register("SourceObject",
  12. typeof(object), typeof(EventTriggerBase), new PropertyMetadata(OnSourceObjectChanged));
  13. private MethodInfo _eventHandlerMethodInfo;
  14. internal EventTriggerBase(Type sourceTypeConstraint) : base(typeof(DependencyObject))
  15. {
  16. SourceTypeConstraint = sourceTypeConstraint;
  17. SourceNameResolver = new NameResolver();
  18. RegisterSourceChanged();
  19. }
  20. protected sealed override Type AssociatedObjectTypeConstraint
  21. {
  22. get
  23. {
  24. if (TypeDescriptor.GetAttributes(GetType())[typeof(TypeConstraintAttribute)] is TypeConstraintAttribute attribute)
  25. return attribute.Constraint;
  26. return typeof(DependencyObject);
  27. }
  28. }
  29. private bool IsLoadedRegistered { get; set; }
  30. private bool IsSourceChangedRegistered { get; set; }
  31. private bool IsSourceNameSet
  32. {
  33. get
  34. {
  35. if (string.IsNullOrEmpty(SourceName))
  36. return ReadLocalValue(SourceNameProperty) != DependencyProperty.UnsetValue;
  37. return true;
  38. }
  39. }
  40. public object Source
  41. {
  42. get
  43. {
  44. object associatedObject = AssociatedObject;
  45. if (SourceObject != null)
  46. return SourceObject;
  47. if (IsSourceNameSet)
  48. {
  49. associatedObject = SourceNameResolver.Object;
  50. if (associatedObject != null && !SourceTypeConstraint.IsInstanceOfType(associatedObject))
  51. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
  52. ExceptionStringTable.RetargetedTypeConstraintViolatedExceptionMessage, GetType().Name,
  53. associatedObject.GetType(), SourceTypeConstraint, "Source"));
  54. }
  55. return associatedObject;
  56. }
  57. }
  58. public string SourceName
  59. {
  60. get =>
  61. (string) GetValue(SourceNameProperty);
  62. set => SetValue(SourceNameProperty, value);
  63. }
  64. private NameResolver SourceNameResolver { get; }
  65. public object SourceObject
  66. {
  67. get =>
  68. GetValue(SourceObjectProperty);
  69. set => SetValue(SourceObjectProperty, value);
  70. }
  71. protected Type SourceTypeConstraint { get; }
  72. protected abstract string GetEventName();
  73. private static bool IsValidEvent(EventInfo eventInfo)
  74. {
  75. var eventHandlerType = eventInfo.EventHandlerType;
  76. if (!typeof(Delegate).IsAssignableFrom(eventInfo.EventHandlerType))
  77. return false;
  78. var parameters = eventHandlerType.GetMethod("Invoke")?.GetParameters();
  79. return parameters != null && parameters.Length == 2 && typeof(object).IsAssignableFrom(parameters[0].ParameterType) && typeof(EventArgs).IsAssignableFrom(parameters[1].ParameterType);
  80. }
  81. protected override void OnAttached()
  82. {
  83. base.OnAttached();
  84. var associatedObject = AssociatedObject;
  85. var behavior = associatedObject as Behavior;
  86. var element = associatedObject as FrameworkElement;
  87. RegisterSourceChanged();
  88. if (behavior != null)
  89. {
  90. behavior.AssociatedObjectChanged += OnBehaviorHostChanged;
  91. }
  92. else if (SourceObject != null || element == null)
  93. {
  94. try
  95. {
  96. OnSourceChanged(null, Source);
  97. }
  98. catch (InvalidOperationException)
  99. {
  100. }
  101. }
  102. else
  103. {
  104. SourceNameResolver.NameScopeReferenceElement = element;
  105. }
  106. if (string.Compare(GetEventName(), "Loaded", StringComparison.Ordinal) == 0 && element != null &&
  107. !Interaction.IsElementLoaded(element))
  108. RegisterLoaded(element);
  109. }
  110. private void OnBehaviorHostChanged(object sender, EventArgs e)
  111. {
  112. SourceNameResolver.NameScopeReferenceElement =
  113. ((IAttachedObject) sender).AssociatedObject as FrameworkElement;
  114. }
  115. protected override void OnDetaching()
  116. {
  117. base.OnDetaching();
  118. var associatedObject = AssociatedObject as Behavior;
  119. var associatedElement = AssociatedObject as FrameworkElement;
  120. try
  121. {
  122. OnSourceChanged(Source, null);
  123. }
  124. catch (InvalidOperationException)
  125. {
  126. }
  127. UnregisterSourceChanged();
  128. if (associatedObject != null)
  129. associatedObject.AssociatedObjectChanged -= OnBehaviorHostChanged;
  130. SourceNameResolver.NameScopeReferenceElement = null;
  131. if (string.Compare(GetEventName(), "Loaded", StringComparison.Ordinal) == 0 && associatedElement != null)
  132. UnregisterLoaded(associatedElement);
  133. }
  134. protected virtual void OnEvent(EventArgs eventArgs)
  135. {
  136. InvokeActions(eventArgs);
  137. }
  138. private void OnEventImpl(object sender, EventArgs eventArgs)
  139. {
  140. OnEvent(eventArgs);
  141. }
  142. internal void OnEventNameChanged(string oldEventName, string newEventName)
  143. {
  144. if (AssociatedObject != null)
  145. {
  146. var source = Source as FrameworkElement;
  147. if (source != null && string.Compare(oldEventName, "Loaded", StringComparison.Ordinal) == 0)
  148. UnregisterLoaded(source);
  149. else if (!string.IsNullOrEmpty(oldEventName))
  150. UnregisterEvent(Source, oldEventName);
  151. if (source != null && string.Compare(newEventName, "Loaded", StringComparison.Ordinal) == 0)
  152. RegisterLoaded(source);
  153. else if (!string.IsNullOrEmpty(newEventName))
  154. RegisterEvent(Source, newEventName);
  155. }
  156. }
  157. private void OnSourceChanged(object oldSource, object newSource)
  158. {
  159. if (AssociatedObject != null)
  160. OnSourceChangedImpl(oldSource, newSource);
  161. }
  162. internal virtual void OnSourceChangedImpl(object oldSource, object newSource)
  163. {
  164. if (!string.IsNullOrEmpty(GetEventName()) &&
  165. string.Compare(GetEventName(), "Loaded", StringComparison.Ordinal) != 0)
  166. {
  167. if (oldSource != null && SourceTypeConstraint.IsInstanceOfType(oldSource))
  168. UnregisterEvent(oldSource, GetEventName());
  169. if (newSource != null && SourceTypeConstraint.IsInstanceOfType(newSource))
  170. RegisterEvent(newSource, GetEventName());
  171. }
  172. }
  173. private static void OnSourceNameChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
  174. {
  175. var base2 = (EventTriggerBase) obj;
  176. base2.SourceNameResolver.Name = (string) args.NewValue;
  177. }
  178. private void OnSourceNameResolverElementChanged(object sender, NameResolvedEventArgs e)
  179. {
  180. if (SourceObject == null)
  181. OnSourceChanged(e.OldObject, e.NewObject);
  182. }
  183. private static void OnSourceObjectChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
  184. {
  185. var base2 = (EventTriggerBase) obj;
  186. object newSource = base2.SourceNameResolver.Object;
  187. if (args.NewValue == null)
  188. {
  189. base2.OnSourceChanged(args.OldValue, newSource);
  190. }
  191. else
  192. {
  193. if (args.OldValue == null && newSource != null)
  194. base2.UnregisterEvent(newSource, base2.GetEventName());
  195. base2.OnSourceChanged(args.OldValue, args.NewValue);
  196. }
  197. }
  198. private void RegisterEvent(object obj, string eventName)
  199. {
  200. var eventInfo = obj.GetType().GetEvent(eventName);
  201. if (eventInfo == null)
  202. {
  203. if (SourceObject != null)
  204. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
  205. ExceptionStringTable.EventTriggerCannotFindEventNameExceptionMessage,
  206. new object[] { eventName, obj.GetType().Name }));
  207. }
  208. else if (!IsValidEvent(eventInfo))
  209. {
  210. if (SourceObject != null)
  211. throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
  212. ExceptionStringTable.EventTriggerBaseInvalidEventExceptionMessage,
  213. new object[] { eventName, obj.GetType().Name }));
  214. }
  215. else
  216. {
  217. _eventHandlerMethodInfo =
  218. typeof(EventTriggerBase).GetMethod("OnEventImpl", BindingFlags.NonPublic | BindingFlags.Instance);
  219. eventInfo.AddEventHandler(obj,
  220. Delegate.CreateDelegate(eventInfo.EventHandlerType, this, _eventHandlerMethodInfo ?? throw new InvalidOperationException()));
  221. }
  222. }
  223. private void RegisterLoaded(FrameworkElement associatedElement)
  224. {
  225. if (!IsLoadedRegistered && associatedElement != null)
  226. {
  227. associatedElement.Loaded += OnEventImpl;
  228. IsLoadedRegistered = true;
  229. }
  230. }
  231. private void RegisterSourceChanged()
  232. {
  233. if (!IsSourceChangedRegistered)
  234. {
  235. SourceNameResolver.ResolvedElementChanged += OnSourceNameResolverElementChanged;
  236. IsSourceChangedRegistered = true;
  237. }
  238. }
  239. private void UnregisterEvent(object obj, string eventName)
  240. {
  241. if (string.Compare(eventName, "Loaded", StringComparison.Ordinal) == 0)
  242. {
  243. if (obj is FrameworkElement associatedElement)
  244. UnregisterLoaded(associatedElement);
  245. }
  246. else
  247. {
  248. UnregisterEventImpl(obj, eventName);
  249. }
  250. }
  251. private void UnregisterEventImpl(object obj, string eventName)
  252. {
  253. var type = obj.GetType();
  254. if (_eventHandlerMethodInfo != null)
  255. {
  256. var info = type.GetEvent(eventName);
  257. info.RemoveEventHandler(obj,
  258. Delegate.CreateDelegate(info.EventHandlerType, this, _eventHandlerMethodInfo));
  259. _eventHandlerMethodInfo = null;
  260. }
  261. }
  262. private void UnregisterLoaded(FrameworkElement associatedElement)
  263. {
  264. if (IsLoadedRegistered && associatedElement != null)
  265. {
  266. associatedElement.Loaded -= OnEventImpl;
  267. IsLoadedRegistered = false;
  268. }
  269. }
  270. private void UnregisterSourceChanged()
  271. {
  272. if (IsSourceChangedRegistered)
  273. {
  274. SourceNameResolver.ResolvedElementChanged -= OnSourceNameResolverElementChanged;
  275. IsSourceChangedRegistered = false;
  276. }
  277. }
  278. }