UWP Navigation with MonoGame page

Hi All! I’m trying to use MonoGame in UWP App where the graphics window is used only in one of the pages of the application. This means that the page may get loaded and unloaded several times as the user interacts with the app. One would expect that the game page setup should be as follows:

public sealed partial class GamePage : Page
    {
		 Game1 _game;

		public GamePage()
        {
            this.InitializeComponent();

            // Create the game.
            var launchArguments = string.Empty;
           _game = MonoGame.Framework.XamlGame<Game1>.Create(launchArguments, Window.Current.CoreWindow, swapChainPanel);
            }


        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
                _game?.SuppressDraw();
                _game?.Dispose();
                _game = null;
        }
  }

This however does not work properly. Once OnNavigatedFrom call is completed, the app raises exception:

System.ObjectDisposedException: The Game1 object was used after being Disposed.
Object name: 'Game1'.
   at Microsoft.Xna.Framework.Game.AssertNotDisposed()
   at Microsoft.Xna.Framework.Game.DoUpdate(GameTime gameTime)
   at Microsoft.Xna.Framework.Game.Tick()
   at Microsoft.Xna.Framework.UAPGameWindow.Tick()
   at Microsoft.Xna.Framework.UAPGamePlatform.<>c.<StartRunLoop>b__12_0(Object o, Object a)

Clearly, the “game” loop is still running despite dispose being called. Is there a way to stop the loop and properly dispose the object, or alterantively work with a singleton object that would be created by the app. Not sure how to do the latter since “SwapChainPanel” has to be passed in the constructor. Any suggestions would be greatly appreciated!

This is a different problem than I had some time ago but the solution might be the same. Check this: https://github.com/MonoGame/MonoGame/issues/6089 (the NavigationCacheMode bit)

Unfortunately I haven’t touched UWP for a year, so I can’t help much more.

Thank you!!! This works perfectly! It would be great if this was part of the documentation for UWP related MonoGame specs as it is very useful for certain scenarios.

I was able to figure out an alternative workaround by creating a singleton that in includes the game but also initializes the SwapChainPanel object. The object then has to be attached to a XAML element in OnNavigatedTo() by SomePanel.Children.Add(MySwapChainPanel) and detached in OnNavigatedFrom() via SomePanel.Children.Remove(MySwapChainPanel). This works as well but the solution above is more elegant.