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.
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;
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... :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With