StyledElementBehaviorOfT.cs 1.3 KB

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