MAUI setting the apps dimensions on a Windows Desktop

I have a MAUI application, designed to an extent as mobile-first. In other words it looks good on a mobile, phone or tablet device in full screen mode. But I really want the app to work and look good (on start up) on Windows Desktop. Ofcourse Windows will just give my main app window a size and I need to do whatever I can to ensure the app looks good.

It’s be so much simpler if I could just set the dimensions of my main window (at start up) to something that looks good. If the user resizes, that’s fine but just starting with a good default makes everything look better.

Okay so that’s the problem at hand, how to solve this?

The first thing is, I thought, I could just change the Platforms/Windows/App.xaml.cs, but nothing obvious there to allow this. If we look at App.xaml.cs we can override the CreateWindow method, so let’s do that – here’s the code

public partial class App : Application
{
  public App()
  {
    InitializeComponent();
    MainPage = new AppShell();
  }

  protected override Window CreateWindow(IActivationState? activationState)
  {
    var window = base.CreateWindow(activationState);

#if WINDOWS
    if (DeviceInfo.Idiom == DeviceIdiom.Desktop)
    {
      window.Width = 500;
      window.Height = 700;
    }
#endif

    return window;
  }
}

It’s pretty self-explanatory, we use conditional compilate using #if WINDOWS to only include the code for a Windows build, but as I also have a Windows tablet I figured I’d also check that the idiom is Desktop before I try to set the window dimensions. All pretty straight forward – although not quite.

The problem is that strangely ANDROID and the likes exist a defines, but seemingly not WINDOWS. We can fix this ourselves in one of two ways.

  • Open the .csproj file and for the net7.0-windowsxxx PropertyGroups add the following
    <DefineConstants>$(DefineConstants);WINDOWS</DefineConstants>
    
  • Open the project’s properties, locate the Build | General then for the “Conditional compilation symbols” for net7.0-windowsxxx entries, add
    $(DefineConstants);WINDOWS
    

This doesn’t fully solve things, well it does but Visual Studio will show the code in Create Window as grayed out as if the conditional compilation directive is excluding the code from the build – it’s not, but it looks that way.

Anyway, now we are able to size the main Window on Windows at start-up.