HamburgerMenu.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. }
  45. private void EnsureSplitViewMode(Rect oldBounds, Rect newBounds)
  46. {
  47. if (_splitView is not null)
  48. {
  49. var threshold = ExpandedModeThresholdWidth;
  50. if (newBounds.Width >= threshold && oldBounds.Width < threshold)
  51. {
  52. _splitView.DisplayMode = SplitViewDisplayMode.Inline;
  53. _splitView.IsPaneOpen = true;
  54. }
  55. else if (newBounds.Width < threshold && oldBounds.Width >= threshold)
  56. {
  57. _splitView.DisplayMode = SplitViewDisplayMode.Overlay;
  58. _splitView.IsPaneOpen = false;
  59. }
  60. }
  61. }
  62. }
  63. }