HamburgerMenu.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using Avalonia;
  2. using Avalonia.Controls;
  3. using Avalonia.Controls.Primitives;
  4. using Avalonia.Media;
  5. namespace ControlSamples
  6. {
  7. public class HamburgerMenu : TabControl
  8. {
  9. private SplitView? _splitView;
  10. public static readonly StyledProperty<IBrush?> PaneBackgroundProperty =
  11. SplitView.PaneBackgroundProperty.AddOwner<HamburgerMenu>();
  12. public IBrush? PaneBackground
  13. {
  14. get => GetValue(PaneBackgroundProperty);
  15. set => SetValue(PaneBackgroundProperty, value);
  16. }
  17. public static readonly StyledProperty<IBrush?> ContentBackgroundProperty =
  18. AvaloniaProperty.Register<HamburgerMenu, IBrush?>(nameof(ContentBackground));
  19. public IBrush? ContentBackground
  20. {
  21. get => GetValue(ContentBackgroundProperty);
  22. set => SetValue(ContentBackgroundProperty, value);
  23. }
  24. public static readonly StyledProperty<int> ExpandedModeThresholdWidthProperty =
  25. AvaloniaProperty.Register<HamburgerMenu, int>(nameof(ExpandedModeThresholdWidth), 1008);
  26. public int ExpandedModeThresholdWidth
  27. {
  28. get => GetValue(ExpandedModeThresholdWidthProperty);
  29. set => SetValue(ExpandedModeThresholdWidthProperty, value);
  30. }
  31. protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
  32. {
  33. base.OnApplyTemplate(e);
  34. _splitView = e.NameScope.Find<SplitView>("PART_NavigationPane");
  35. }
  36. protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
  37. {
  38. base.OnPropertyChanged(change);
  39. if (change.Property == BoundsProperty && _splitView is not null)
  40. {
  41. var (oldBounds, newBounds) = change.GetOldAndNewValue<Rect>();
  42. EnsureSplitViewMode(oldBounds, newBounds);
  43. }
  44. if (change.Property == SelectedItemProperty)
  45. {
  46. if (_splitView is not null && _splitView.DisplayMode == SplitViewDisplayMode.Overlay)
  47. {
  48. _splitView.SetCurrentValue(SplitView.IsPaneOpenProperty, false);
  49. }
  50. }
  51. }
  52. private void EnsureSplitViewMode(Rect oldBounds, Rect newBounds)
  53. {
  54. if (_splitView is not null)
  55. {
  56. var threshold = ExpandedModeThresholdWidth;
  57. if (newBounds.Width >= threshold)
  58. {
  59. _splitView.DisplayMode = SplitViewDisplayMode.Inline;
  60. _splitView.IsPaneOpen = true;
  61. }
  62. else if (newBounds.Width < threshold)
  63. {
  64. _splitView.DisplayMode = SplitViewDisplayMode.Overlay;
  65. _splitView.IsPaneOpen = false;
  66. }
  67. }
  68. }
  69. }
  70. }