Hello,
Welcome to Microsoft Q&A.
When we use Frame.Navigate(typeof(SomePage))
, by default, a new instance is generated based on the type of this Page. So multiple navigations actually creates multiple instances.
When the page is navigated, the previous page will not be released, because for the Frame
, a history record is required, which will retain a reference to the page
If we want to limit this situation, we can cache the page:
private bool _isLoaded = false;
public ListsPage()
{
_secondPageViewModel = new SecondPageViewModel();
NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
InitializeComponent();
Loaded += async (sender, args) =>
{
if (!_isLoaded)
{
_isLoaded = true;
await _secondPageViewModel.Init();
}
};
}
After the page is cached, navigate to the page again, and Frame will use the cache first. This means that no new page instances will be created, and the memory usage will not increase.
---
Update
In your question, you did not use Frame
for page navigation (sorry, this is my oversight).
Even so, caching pages is still a solution to the problem.
Simply put, every time you call App.NavigateTo(Type)
, you recreate the instance of a page based on this Type.
Every time a ListsPage
is created, a List<StringList>
will be regenerated, and the memory overhead is mainly used to create the corresponding ListView
.
So as an alternative to caching, we can create a FrameworkElement
list. When the page is first created, the page will be stored in the list. The next time we navigate, we can check the list and take out our previous cache instead of creating a new one.
private List<FrameworkElement> _pageList;
public App()
{
_pageStack = new Stack<Type>();
_pageList = new List<FrameworkElement>();
InitializeComponent();
}
//...
private void ChangeWindowContent(Type type)
{
if (_pageList.Any(p => p.GetType().Equals(type)))
Window.Current.Content = _pageList.Where(p => p.GetType().Equals(type)).First();
else
{
var page= (FrameworkElement)Activator.CreateInstance(type);
_pageList.Add(page);
Window.Current.Content = page;
}
SystemNavigationManager systemNavigationManager = SystemNavigationManager.GetForCurrentView();
systemNavigationManager.AppViewBackButtonVisibility = CanGoBack
? AppViewBackButtonVisibility.Visible
: AppViewBackButtonVisibility.Disabled;
}
In this way, by calling the previous cache, we can avoid the additional overhead caused by repeatedly creating instances.
In ListsPage
, please use the previous reply to modify the Loaded event to avoid repeated creation of List<StringList>
Thanks.
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.