TriggerOfT.cs 1.2 KB

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