Skip to content
34 changes: 34 additions & 0 deletions WinUIGallery/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,46 @@ public NavigationView NavigationView

public Action NavigationViewLoaded { get; set; }

#nullable enable
private OverlappedPresenter? WindowPresenter { get; }
#nullable disable

private OverlappedPresenterState CurrentWindowState { get; set; }

public MainWindow()
{
this.InitializeComponent();
SetWindowProperties();
RootGrid.ActualThemeChanged += (_, _) => TitleBarHelper.ApplySystemThemeToCaptionButtons(this, RootGrid.ActualTheme);
dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

// Workaround for WinUI issue #9934:
// https://github.com/microsoft/microsoft-ui-xaml/issues/9934.
// See `AdjustNavigationViewMargin()` for implementation details.
if (AppWindow.Presenter is OverlappedPresenter windowPresenter)
{
WindowPresenter = windowPresenter;
CurrentWindowState = WindowPresenter.State;
AdjustNavigationViewMargin(force: true);
AppWindow.Changed += (_, _) => AdjustNavigationViewMargin();
}
}

// Adjusts the NavigationView margin based on the window state
// to fix the gap between the caption buttons and the NavigationView.
// Use `force = true` to ensure adjustment on the first call.
private void AdjustNavigationViewMargin(bool? force = null)
{
if (WindowPresenter is null ||
(WindowPresenter.State == CurrentWindowState && force is not true))
{
return;
}

NavigationView.Margin = WindowPresenter.State == OverlappedPresenterState.Maximized
? new Thickness(0, -1, 0, 0)
: new Thickness(0, -2, 0, 0);
CurrentWindowState = WindowPresenter.State;
}

private void RootGrid_Loaded(object sender, RoutedEventArgs e)
Expand Down