UWP中Page的重用

在写UWP应用时,遇到频繁进出相同Page的情况可以考虑Page的重用
翻阅微软的官方文档时找到了Page重用的方法,部分原文如下:

By default, each navigation creates a new instance of the specific Page subclass requested, and disposes the previous page instance. This happens even when navigating back to a previously visited page or when the new page type is the same as the previous page type. Apps that involve frequent navigation to the same pages can cache and reuse the page instances to make navigation more efficient. To do this, set the CacheSize property to specify how many pages to cache. For each page type that you want to cache, you must also set the Page.NavigationCacheMode property to either Enabled or Required. Pages with a Required cache mode are cached regardless of the CacheSize value, and do not count against the CacheSize total.

默认情况下,每次导航都会新建Page并销毁之前的Page,即便是导航回之前访问过的Page或者新Page的类型同之前Page的类型相同也是如此。对于频繁导航至相同页面的应用,可以通过缓存、重用Page来提高导航效率。为此,需要设置Frame.CacheSize指定缓存的Page数量。对于每一个需要缓存的Page,需要将Page.NavigationCacheMode 设置为‘Enable’或‘Required’。若设置为‘Required’,该页面缓存时将无视CacheSize,不计入CacheSize总数。

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    NavigationCacheMode="Required">

以上为一种方法。

另外NavigationEventArgs.NavigationMode指示了导航的模式(类型),可以判断是新进入该页面还是从之后的页面返回到该页面的。NavigationMode包括Back、Forward、New、Refresh,详见官方文档

猜你喜欢

转载自blog.csdn.net/funnywhitecat/article/details/76302055
UWP