Behavior.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System;
  2. using System.Globalization;
  3. using System.Windows;
  4. using System.Windows.Media.Animation;
  5. namespace HandyControl.Interactivity;
  6. public abstract class Behavior : Animatable, IAttachedObject
  7. {
  8. private DependencyObject _associatedObject;
  9. private readonly Type _associatedType;
  10. internal Behavior(Type associatedType)
  11. {
  12. _associatedType = associatedType;
  13. }
  14. protected DependencyObject AssociatedObject
  15. {
  16. get
  17. {
  18. ReadPreamble();
  19. return _associatedObject;
  20. }
  21. }
  22. protected Type AssociatedType
  23. {
  24. get
  25. {
  26. ReadPreamble();
  27. return _associatedType;
  28. }
  29. }
  30. public void Attach(DependencyObject dependencyObject)
  31. {
  32. if (!Equals(dependencyObject, AssociatedObject))
  33. {
  34. if (AssociatedObject != null)
  35. throw new InvalidOperationException(ExceptionStringTable
  36. .CannotHostBehaviorMultipleTimesExceptionMessage);
  37. if (dependencyObject != null && !AssociatedType.IsInstanceOfType(dependencyObject))
  38. throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture,
  39. ExceptionStringTable.TypeConstraintViolatedExceptionMessage,
  40. new object[] { GetType().Name, dependencyObject.GetType().Name, AssociatedType.Name }));
  41. WritePreamble();
  42. _associatedObject = dependencyObject;
  43. WritePostscript();
  44. OnAssociatedObjectChanged();
  45. OnAttached();
  46. }
  47. }
  48. public void Detach()
  49. {
  50. OnDetaching();
  51. WritePreamble();
  52. _associatedObject = null;
  53. WritePostscript();
  54. OnAssociatedObjectChanged();
  55. }
  56. DependencyObject IAttachedObject.AssociatedObject =>
  57. AssociatedObject;
  58. internal event EventHandler AssociatedObjectChanged;
  59. protected override Freezable CreateInstanceCore()
  60. {
  61. return (Freezable) Activator.CreateInstance(GetType());
  62. }
  63. private void OnAssociatedObjectChanged()
  64. {
  65. AssociatedObjectChanged?.Invoke(this, new EventArgs());
  66. }
  67. protected virtual void OnAttached()
  68. {
  69. }
  70. protected virtual void OnDetaching()
  71. {
  72. }
  73. }