Best way to access current instance of MainPage in a Windows Store app?

Danny Johnson picture Danny Johnson · Jul 9, 2013 · Viewed 12.5k times · Source

I was wondering how one could access the current instance of the main page from a different class in a C# Windows Store app.

Specifically, in a Windows Store app for a Surface RT tablet (so, limited to RT API) I want to access mainpage methods and UI elements from other classes.

Creating a new instance works, like this:

MainPage mp = new MainPage();
mp.PublicMainPageMethod();
mp.mainpageTextBlock.Text = "Setting text at runtime";

in that it exposes the methods / UI elements, but this can't be the proper procedure.

What is the best practice for accessing methods and modifying UI elements on the main page at runtime, from other classes? There are several articles about this for Windows Phone but I can't seem to find anything for Windows RT.

Answer

takemyoxygen picture takemyoxygen · Jul 9, 2013

I agree that it's better to use MVVM pattern, but just in case you need to get current page you can do it as follows:

  var frame = (Frame)Window.Current.Content;
  var page = (MainPage)frame.Content;