Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 309
Danny Johnson Avatar asked Jul 09 '13 19:07

Danny Johnson


2 Answers

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;
like image 64
takemyoxygen Avatar answered Nov 20 '22 04:11

takemyoxygen


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... :)

like image 43
Rudi Avatar answered Nov 20 '22 04:11

Rudi