ValueChangedTriggerBehavior.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. using Avalonia.Reactive;
  2. using Avalonia.Xaml.Interactivity;
  3. namespace Avalonia.Xaml.Interactions.Custom;
  4. /// <summary>
  5. /// A behavior that performs actions when the bound data produces new value.
  6. /// </summary>
  7. public class ValueChangedTriggerBehavior : StyledElementTrigger
  8. {
  9. static ValueChangedTriggerBehavior()
  10. {
  11. BindingProperty.Changed.Subscribe(
  12. new AnonymousObserver<AvaloniaPropertyChangedEventArgs<object?>>(OnValueChanged));
  13. }
  14. /// <summary>
  15. /// Identifies the <seealso cref="Binding"/> avalonia property.
  16. /// </summary>
  17. public static readonly StyledProperty<object?> BindingProperty =
  18. AvaloniaProperty.Register<ValueChangedTriggerBehavior, object?>(nameof(Binding));
  19. /// <summary>
  20. /// Gets or sets the bound object that the <see cref="ValueChangedTriggerBehavior"/> will listen to. This is a avalonia property.
  21. /// </summary>
  22. public object? Binding
  23. {
  24. get => GetValue(BindingProperty);
  25. set => SetValue(BindingProperty, value);
  26. }
  27. private static void OnValueChanged(AvaloniaPropertyChangedEventArgs args)
  28. {
  29. if (args.Sender is not ValueChangedTriggerBehavior behavior || behavior.AssociatedObject is null)
  30. {
  31. return;
  32. }
  33. if (!behavior.IsEnabled)
  34. {
  35. return;
  36. }
  37. var binding = behavior.Binding;
  38. if (binding is not null)
  39. {
  40. Interaction.ExecuteActions(behavior.AssociatedObject, behavior.Actions, args);
  41. }
  42. }
  43. }