FadeInBehavior.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using Avalonia.Animation;
  3. using Avalonia.Styling;
  4. using System.Reactive.Disposables;
  5. namespace Avalonia.Xaml.Interactions.Custom;
  6. /// <summary>
  7. ///
  8. /// </summary>
  9. public class FadeInBehavior : AttachedToVisualTreeBehavior<Visual>
  10. {
  11. /// <summary>
  12. ///
  13. /// </summary>
  14. public static readonly StyledProperty<TimeSpan> InitialDelayProperty =
  15. AvaloniaProperty.Register<FadeInBehavior, TimeSpan>(nameof(InitialDelay), TimeSpan.FromMilliseconds(500));
  16. /// <summary>
  17. ///
  18. /// </summary>
  19. public static readonly StyledProperty<TimeSpan> DurationProperty =
  20. AvaloniaProperty.Register<FadeInBehavior, TimeSpan>(nameof(Duration), TimeSpan.FromMilliseconds(250));
  21. /// <summary>
  22. ///
  23. /// </summary>
  24. public TimeSpan InitialDelay
  25. {
  26. get => GetValue(InitialDelayProperty);
  27. set => SetValue(InitialDelayProperty, value);
  28. }
  29. /// <summary>
  30. ///
  31. /// </summary>
  32. public TimeSpan Duration
  33. {
  34. get => GetValue(DurationProperty);
  35. set => SetValue(DurationProperty, value);
  36. }
  37. /// <summary>
  38. ///
  39. /// </summary>
  40. /// <param name="disposable"></param>
  41. protected override void OnAttachedToVisualTree(CompositeDisposable disposable)
  42. {
  43. if (AssociatedObject is null)
  44. {
  45. return;
  46. }
  47. var totalDuration = InitialDelay + Duration;
  48. var animation = new Animation.Animation
  49. {
  50. Duration = totalDuration,
  51. Children =
  52. {
  53. new KeyFrame {KeyTime = TimeSpan.Zero, Setters = {new Setter(Visual.OpacityProperty, 0d),}},
  54. new KeyFrame {KeyTime = InitialDelay, Setters = {new Setter(Visual.OpacityProperty, 0d),}},
  55. new KeyFrame {KeyTime = Duration, Setters = {new Setter(Visual.OpacityProperty, 1d),}}
  56. }
  57. };
  58. animation.RunAsync(AssociatedObject);
  59. }
  60. }