BehaviorOfT.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. using System;
  2. namespace Avalonia.Xaml.Interactivity;
  3. /// <summary>
  4. /// A base class for behaviors making them code compatible with older frameworks,
  5. /// and allow for typed associated objects.
  6. /// </summary>
  7. /// <typeparam name="T">The object type to attach to</typeparam>
  8. public abstract class Behavior<T> : Behavior where T : AvaloniaObject
  9. {
  10. /// <summary>
  11. /// Gets the object to which this behavior is attached.
  12. /// </summary>
  13. public new T? AssociatedObject => base.AssociatedObject as T;
  14. /// <summary>
  15. /// Called after the behavior is attached to the <see cref="IBehavior.AssociatedObject"/>.
  16. /// </summary>
  17. /// <remarks>
  18. /// Override this to hook up functionality to the <see cref="IBehavior.AssociatedObject"/>
  19. /// </remarks>
  20. protected override void OnAttached()
  21. {
  22. base.OnAttached();
  23. if (AssociatedObject is null && base.AssociatedObject is not null)
  24. {
  25. var actualType = base.AssociatedObject?.GetType().FullName;
  26. var expectedType = typeof(T).FullName;
  27. var message = $"AssociatedObject is of type {actualType} but should be of type {expectedType}.";
  28. throw new InvalidOperationException(message);
  29. }
  30. }
  31. }