CommandBarKeyboardPage.xaml.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using Avalonia.Controls;
  4. using Avalonia.Input;
  5. using Avalonia.Interactivity;
  6. namespace ControlCatalog.Pages
  7. {
  8. public partial class CommandBarKeyboardPage : UserControl
  9. {
  10. private readonly List<string> _log = new();
  11. public CommandBarKeyboardPage()
  12. {
  13. InitializeComponent();
  14. Loaded += OnLoaded;
  15. Unloaded += OnUnloaded;
  16. }
  17. private void OnLoaded(object? sender, RoutedEventArgs e)
  18. {
  19. DemoBar.Opened += OnOpened;
  20. DemoBar.Closed += OnClosed;
  21. BtnCopy.GotFocus += OnItemFocused;
  22. BtnPaste.GotFocus += OnItemFocused;
  23. BtnBold.GotFocus += OnItemFocused;
  24. BtnShare.GotFocus += OnItemFocused;
  25. BtnDelete.GotFocus += OnItemFocused;
  26. BtnExport.GotFocus += OnItemFocused;
  27. }
  28. private void OnUnloaded(object? sender, RoutedEventArgs e)
  29. {
  30. DemoBar.Opened -= OnOpened;
  31. DemoBar.Closed -= OnClosed;
  32. BtnCopy.GotFocus -= OnItemFocused;
  33. BtnPaste.GotFocus -= OnItemFocused;
  34. BtnBold.GotFocus -= OnItemFocused;
  35. BtnShare.GotFocus -= OnItemFocused;
  36. BtnDelete.GotFocus -= OnItemFocused;
  37. BtnExport.GotFocus -= OnItemFocused;
  38. }
  39. private void OnOpened(object? sender, RoutedEventArgs e)
  40. => AppendLog("Opened. Use arrow keys to navigate.");
  41. private void OnClosed(object? sender, RoutedEventArgs e)
  42. => AppendLog("Closed");
  43. private void OnItemFocused(object? sender, FocusChangedEventArgs e)
  44. {
  45. var label = sender switch
  46. {
  47. CommandBarButton btn => btn.Label ?? "(unnamed)",
  48. CommandBarToggleButton t => t.Label ?? "(unnamed)",
  49. _ => sender?.GetType().Name ?? "?"
  50. };
  51. var method = e.NavigationMethod switch
  52. {
  53. NavigationMethod.Directional => "arrow key",
  54. NavigationMethod.Tab => "Tab",
  55. NavigationMethod.Pointer => "pointer",
  56. _ => "unspecified"
  57. };
  58. AppendLog($"Focus: {label} ({method})");
  59. }
  60. private void OnOpenOverflow(object? sender, RoutedEventArgs e)
  61. {
  62. DemoBar.IsOpen = true;
  63. }
  64. private void OnClearLog(object? sender, RoutedEventArgs e)
  65. {
  66. _log.Clear();
  67. FocusLogText.Text = "Log cleared.";
  68. }
  69. private void AppendLog(string message)
  70. {
  71. _log.Add(message);
  72. if (_log.Count > 10)
  73. _log.RemoveAt(0);
  74. FocusLogText.Text = string.Join("\n", _log.Select((entry, i) => $"{i + 1,2}. {entry}"));
  75. }
  76. }
  77. }