Is there a way to access cached pages from a Frame in WinUI 3

208 views Asked by At

I have an application that uses a navigation view to switch between 4 pages, 2 of which hold data, that are cached by a Frame. I'm implementing a save function that pulls the data from both of these 'data pages', but I don't know how to access the cached page instances from the frame.

I tried manually storing the page instances in private fields in the main window class, but that didn't work.

1

There are 1 answers

0
Abdessattar On BEST ANSWER

The pattern for this is to have MVVM and use the ViewModel to manage the data for the view (the page). One of the reasons for that (besides the usual reasons for MVVM) is that WinUI navigation creates a new instance of the page you navigate to every time you do so.

If you do use MVVM, the the ViewModel creation is your responsibility and you could opt to have a single instance of the view models that will keep the data for the view persistent across navigations.

If for some reason you don't like or can't use MVVM, then there is another fallback pattern, services. You would make a service responsible for managing the data for pages and use it every time you navigate to a page (WinUI offers an event, Navigated, for that). In this scenario, you would use the service instance (usually from a DI) in the page when you navigate into it to load the data and setup the presentation.

Note there is always the option of storing the data, as you mentioned, at the frame level and create a dependency between the pages and their frame through child->parent relationships but this method is really ugly, not intuitive in the XAML tree and absolutely not recommended. A view/page should not know who contains it.