FocusControlAction.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using Avalonia.Controls;
  2. using Avalonia.Threading;
  3. using Avalonia.Xaml.Interactivity;
  4. namespace Avalonia.Xaml.Interactions.Custom;
  5. /// <summary>
  6. /// Focuses the associated or target control when executed.
  7. /// </summary>
  8. public class FocusControlAction : Avalonia.Xaml.Interactivity.Action
  9. {
  10. /// <summary>
  11. /// Identifies the <seealso cref="TargetControl"/> avalonia property.
  12. /// </summary>
  13. public static readonly StyledProperty<Control?> TargetControlProperty =
  14. AvaloniaProperty.Register<FocusControlAction, Control?>(nameof(TargetControl));
  15. /// <summary>
  16. /// Gets or sets the target control. This is a avalonia property.
  17. /// </summary>
  18. [ResolveByName]
  19. public Control? TargetControl
  20. {
  21. get => GetValue(TargetControlProperty);
  22. set => SetValue(TargetControlProperty, value);
  23. }
  24. /// <summary>
  25. /// Executes the action.
  26. /// </summary>
  27. /// <param name="sender">The <see cref="object"/> that is passed to the action by the behavior. Generally this is <seealso cref="IBehavior.AssociatedObject"/> or a target object.</param>
  28. /// <param name="parameter">The value of this parameter is determined by the caller.</param>
  29. /// <returns>Returns null after executed.</returns>
  30. public override object? Execute(object? sender, object? parameter)
  31. {
  32. if (!IsEnabled)
  33. {
  34. return false;
  35. }
  36. var control = TargetControl ?? sender as Control;
  37. Dispatcher.UIThread.Post(() => control?.Focus());
  38. return null;
  39. }
  40. }