Best way to access current instance of MainPage in a Windows Store app?
c#, windows-store-apps
Solution
If you're using MVVM, you can use the Messenger class:
MainWindow.xaml:
using GalaSoft.MvvmLight.Messaging;
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainViewModel();
Messenger.Default.Register<NotificationMessage>(this, (nm) =>
{
//Check which message you've sent
if (nm.Notification == "CloseWindowsBoundToMe")
{
//If the DataContext is the same ViewModel where you've called the Messenger
if (nm.Sender == this.DataContext)
//Do something here, for example call a function. I'm closing the view:
this.Close();
}
});
}
And in your ViewModel, you can call the Messenger or notify your View any time:
Messenger.Default.Send<NotificationMessage>(new NotificationMessage(this, "CloseWindowsBoundToMe"));
pretty easy... :)
Problem
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.