简体   繁体   中英

How to share property between multiple pages / pass by reference in navigation?

I am writing a UWP program, and I wish to share a common property/field between multiple pages. I tried to create a model(or maybe viewmodel) instance in the parent page and pass the instance to the children page as a parameter of Frame.Navigate method. However, since parameters in C# are passed by value, and Frame.Navigate does not support reference or out, I expect it does not work to actually share this instance between multiple pages.

My questions are

  1. Is this the common practice for sharing values between pages, and will it work?
  2. If not, what is the suggested approach?
  3. If it is, why does it work?

If you want to share same values of one model between multiple pages then make your model as static class. So that they will share single copy of it.

If the value is modified page by page then you can pass the object of the model and can retrieve the same in OnNavigatedTo of the next page

 ItemModel objEditItem;
    protected override void OnNavigatedTo(NavigationEventArgs e)
    {

        if (e.Parameter != null)
        {
            objEditItem = new ItemModel();
            objEditItem = e.Parameter as ItemModel;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM