Daniel
Daniel

Reputation: 273

How to read/write in a parent frame's variable in UWP?

In my MainPage.xaml I've got a SplitView that loads many pages inside a frame created in it's SlplitView.Content.

I've got data in a MainPage's variable that needs to be sent to every page that loads in my SplitView content's frame according to the ListBoxItem clicked.

Also in the current page I may have to update the MainPage's variable before a new page is loaded.

How can I do this? Is there a way to declare a global variable? Can I transport that information from a page to another updating it's value on the parent page?

Upvotes: 1

Views: 3304

Answers (2)

Daniel
Daniel

Reputation: 273

Complementing the last answer I solved my problem by declaring an internal static variable in my "App.xaml.cs".

internal static string foo = "";

Then to access it I used:

App.foo = "my string";

There is also a more elegant way to preserve and restore page data when leaving it (which is what I needed) as follows: https://msdn.microsoft.com/pt-br/library/windows/apps/ff967548%28v=vs.105%29.aspx

Upvotes: 1

Alan Yao - MSFT
Alan Yao - MSFT

Reputation: 3304

I think you can declare a public static variable in App Class in App.xaml.cs, and use it in any pages in the app.

In App.xaml.cs:

sealed partial class App : Application
{
    ...
    public static string MyTestVar { get; set; }
    ...
}

In MainPage.xaml.cs:

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();
        App.MyTestVar = "world";
    }
}

And for some other cases like implementing a setting page, you can check Store and retrieve settings and other app data.

Upvotes: 4

Related Questions