Sharing your view model between Monogame and XAML

If you create a new Monogame Windows Store XAML Project. You will get a XAML page called GamePage.xaml and you'll get the monogame game class Game1.cs. If you want display data from your game class in XAML or if you want to take input from XAML into your game then these two sides are going to need to communicate.

One way they can communicate is by sharing a view model. As the XAML page creates the instance of your game class, it can also let your game class know about it's view model. Like this in GamePage.xaml.cs:

public GamePage(string launchArguments)
{
    this.InitializeComponent();

    // Create the game
    _game = XamlGame<Game1>.Create(launchArguments, Window.Current.CoreWindow, this);
_game.XamlGameDataViewModel = new GameDataViewModel();
DataContext = _game.XamlGameDataViewModel;
}

GameDataViewModel is a view model class of my own creation and can be whatever you need it to be. If you want the XAML to know when the properties in the class have been updated then you'll need to make the properties observable. This will however make this code less reusable across different platforms. You can also include event methods that get called by the XAML. Once again this makes the view model platform specific.

In your game class you just need to include a public property for your view model that can be set by GamePage. You can then refer to the data in that view model in your game class.