StyledElementTriggerOfT.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Diagnostics.CodeAnalysis;
  3. using Avalonia.Metadata;
  4. namespace Avalonia.Xaml.Interactivity;
  5. /// <summary>
  6. /// A base class for behaviors, implementing the basic plumbing of <seealso cref="ITrigger"/>.
  7. /// </summary>
  8. /// <typeparam name="T">The object type to attach to</typeparam>
  9. public abstract class StyledElementTrigger<T> : StyledElementTrigger 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="IBehavior.AssociatedObject"/>.
  17. /// </summary>
  18. /// <remarks>
  19. /// Override this to hook up functionality to the <see cref="IBehavior.AssociatedObject"/>
  20. /// </remarks>
  21. ///
  22. protected override void OnAttached()
  23. {
  24. base.OnAttached();
  25. if (AssociatedObject is null && base.AssociatedObject is not null)
  26. {
  27. var actualType = base.AssociatedObject?.GetType().FullName;
  28. var expectedType = typeof(T).FullName;
  29. var message = $"AssociatedObject is of type {actualType} but should be of type {expectedType}.";
  30. throw new InvalidOperationException(message);
  31. }
  32. }
  33. }