FocusAutoCompleteBoxTextBoxBehavior.cs 940 B

123456789101112131415161718192021222324252627282930313233
  1. using System.Linq;
  2. using System.Reactive.Disposables;
  3. using Avalonia.Controls;
  4. using Avalonia.Input;
  5. using Avalonia.Threading;
  6. using Avalonia.VisualTree;
  7. namespace Avalonia.Xaml.Interactions.Custom;
  8. /// <summary>
  9. ///
  10. /// </summary>
  11. public class FocusAutoCompleteBoxTextBoxBehavior : AttachedToVisualTreeBehavior<AutoCompleteBox>
  12. {
  13. /// <inheritdoc />
  14. protected override void OnAttachedToVisualTree(CompositeDisposable disposable)
  15. {
  16. if (AssociatedObject is null)
  17. {
  18. return;
  19. }
  20. AssociatedObject.GotFocus += AssociatedObjectOnGotFocus;
  21. Disposable.Create(() => AssociatedObject.GotFocus -= AssociatedObjectOnGotFocus);
  22. }
  23. private void AssociatedObjectOnGotFocus(object? sender, GotFocusEventArgs e)
  24. {
  25. var textBox = AssociatedObject?.GetVisualDescendants().OfType<TextBox>().FirstOrDefault();
  26. Dispatcher.UIThread.Post(() => textBox?.Focus());
  27. }
  28. }