巡覽概觀Navigation Overview

Windows Presentation Foundation (WPF)支援瀏覽器樣式的導覽,可用於兩種類型的應用程式:獨立應用程式和 XAML 瀏覽器應用程式(Xbap)。Windows Presentation Foundation (WPF) supports browser-style navigation that can be used in two types of applications: standalone applications and XAML browser applications (XBAPs). 為了要封裝內容以進行導覽,WPF 提供了 Page 類別。To package content for navigation, WPF provides the Page class. 您可以使用 Hyperlink,或以程式設計方式從一個 Page 導覽至另一個,方法是使用 NavigationServiceYou can navigate from one Page to another declaratively, by using a Hyperlink, or programmatically, by using the NavigationService. WPF 會使用日誌來記住已從流覽的頁面,並流覽回它們。WPF uses the journal to remember pages that have been navigated from and to navigate back to them.

PageHyperlinkNavigationService和日誌形成 WPF 所提供的導覽支援的核心。Page, Hyperlink, NavigationService, and the journal form the core of the navigation support offered by WPF. 本總覽會在涵蓋先進的導覽支援(包括流覽到鬆散 Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) 檔案、HTML 檔案和物件)之前,先深入探索這些功能。This overview explores these features in detail before covering advanced navigation support that includes navigation to loose Extensible Application Markup Language (XAML)Extensible Application Markup Language (XAML) files, HTML files, and objects.

注意

在本主題中,「瀏覽器」一詞只是指可以裝載 WPF 應用程式的瀏覽器,其中目前包含 Microsoft Internet Explorer 和 Firefox。In this topic, the term "browser" refers only to browsers that can host WPF applications, which currently includes Microsoft Internet Explorer and Firefox. 只有特定的瀏覽器支援特定的 WPF 功能時,才會參考瀏覽器版本。Where specific WPF features are supported only by a particular browser, the browser version is referred to.

本主題提供 WPF 中主要導覽功能的總覽。This topic provides an overview of the key navigation capabilities in WPF. 這些功能都可供獨立應用程式和 Xbap 使用,雖然本主題會在 XBAP 的內容中呈現它們。These capabilities are available to both standalone applications and XBAPs, although this topic presents them within the context of an XBAP.

注意

本主題不會討論如何建立和部署 Xbap。This topic doesn't discuss how to build and deploy XBAPs. 如需 Xbap 的詳細資訊,請參閱WPF XAML 瀏覽器應用程式總覽For more information on XBAPs, see WPF XAML Browser Applications Overview.

本節說明並示範下列巡覽的各個面向︰This section explains and demonstrates the following aspects of navigation:

實作頁面Implementing a Page

在 WPF 中,您可以導覽至數種內容類型,其中包括 .NET Framework 物件、自訂物件、列舉值、使用者控制項、XAMLXAML 檔案和 HTML 檔案。In WPF, you can navigate to several content types that include .NET Framework objects, custom objects, enumeration values, user controls, XAMLXAML files, and HTML files. 不過,您會發現封裝內容最常見且方便的方式,就是使用 PageHowever, you'll find that the most common and convenient way to package content is by using Page. 此外,Page 會執行導覽特有的功能,以增強其外觀並簡化開發。Furthermore, Page implements navigation-specific features to enhance their appearance and simplify development.

使用 Page,您可以使用如下所示的標記,以宣告方式執行 XAMLXAML 內容的可導覽頁面。Using Page, you can declaratively implement a navigable page of XAMLXAML content by using markup like the following.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" />

XAMLXAML 標記中執行的 PagePage 做為其根項目,而且需要 WPF XML 命名空間宣告。A Page that is implemented in XAMLXAML markup has Page as its root element and requires the WPF XML namespace declaration. Page 元素包含您要流覽和顯示的內容。The Page element contains the content that you want to navigate to and display. 您可以藉由設定 Page.Content 屬性元素來新增內容,如下列標記所示。You add content by setting the Page.Content property element, as shown in the following markup.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Page.Content>
    <!-- Page Content -->
    Hello, Page!
  </Page.Content>
</Page>

Page.Content 只能包含一個子項目。在上例中,內容是單一字串 "Hello, Page!"Page.Content can only contain one child element; in the preceding example, the content is a single string, "Hello, Page!" 在實務上,您通常會使用版面配置控制項做為子專案(請參閱版面配置)以包含及撰寫內容。In practice, you will usually use a layout control as the child element (see Layout) to contain and compose your content.

Page 專案的子項目會被視為 Page 的內容,因此,您不需要使用明確的 Page.Content 宣告。The child elements of a Page element are considered to be the content of a Page and, consequently, you don't need to use the explicit Page.Content declaration. 下列標記是前例的宣告式對等項目。The following markup is the declarative equivalent to the preceding sample.

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <!-- Page Content -->
  Hello, Page!
</Page>

在此情況下,Page.Content 會自動設定 Page 元素的子項目。In this case, Page.Content is automatically set with the child elements of the Page element. 如需詳細資訊,請參閱 WPF 內容模型For more information, see WPF Content Model.

僅限標記的 Page 適用于顯示內容。A markup-only Page is useful for displaying content. 不過,Page 也可以顯示可讓使用者與頁面互動的控制項,而且它可以藉由處理事件和呼叫應用程式邏輯來回應使用者互動。However, a Page can also display controls that allow users to interact with the page, and it can respond to user interaction by handling events and calling application logic. 互動式 Page 是使用標記和程式碼後置的組合來執行,如下列範例所示。An interactive Page is implemented by using a combination of markup and code-behind, as shown in the following example.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.HomePage">
  Hello, from the XBAP HomePage!
</Page>
using System.Windows.Controls;

namespace SDKSample
{
    public partial class HomePage : Page
    {
        public HomePage()
        {
            InitializeComponent();
        }
    }
}

Imports System.Windows.Controls

Namespace SDKSample
    Partial Public Class HomePage
        Inherits Page
        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace

若要讓標記檔案和程式碼後置檔案一起工作,需要設定下列項目:To allow a markup file and code-behind file to work together, the following configuration is required:

  • 在標記中,Page 元素必須包含 x:Class 屬性。In markup, the Page element must include the x:Class attribute. 建立應用程式時,標記檔案中的 x:Class 存在,會導致 Microsoft build engine (MSBuild)建立衍生自 Pagepartial 類別,且其名稱是由 x:Class 屬性所指定。When the application is built, the existence of x:Class in the markup file causes Microsoft build engine (MSBuild) to create a partial class that derives from Page and has the name that is specified by the x:Class attribute. 這需要加入 XAMLXAML 架構(xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml")的 XML 命名空間宣告。This requires the addition of an XML namespace declaration for the XAMLXAML schema ( xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" ). 產生的 partial 類別會執行 InitializeComponent,這會呼叫來註冊事件,並設定在標記中執行的屬性。The generated partial class implements InitializeComponent, which is called to register the events and set the properties that are implemented in markup.

  • 在程式碼後置中,類別必須是具有與標記中 x:Class 屬性所指定相同名稱的 partial 類別,而且必須衍生自 PageIn code-behind, the class must be a partial class with the same name that is specified by the x:Class attribute in markup, and it must derive from Page. 這可讓程式碼後置檔案與建立應用程式時為標記檔案產生的 partial 類別相關聯(請參閱建立 WPF 應用程式)。This allows the code-behind file to be associated with the partial class that is generated for the markup file when the application is built (see Building a WPF Application).

  • 在程式碼後置中,Page 類別必須執行呼叫 InitializeComponent 方法的函式。In code-behind, the Page class must implement a constructor that calls the InitializeComponent method. InitializeComponent 由標記檔案產生的 partial 類別來執行,以註冊事件並設定在標記中定義的屬性。InitializeComponent is implemented by the markup file's generated partial class to register events and set properties that are defined in markup.

注意

當您使用 Visual Studio 將新的 Page 新增至專案時,會使用標記和程式碼後置來實作為 Page,並包含必要的設定來建立標記和程式碼後置檔案之間的關聯,如這裡所述。When you add a new Page to your project using Visual Studio, the Page is implemented using both markup and code-behind, and it includes the necessary configuration to create the association between the markup and code-behind files as described here.

一旦有了 Page,您就可以流覽至它。Once you have a Page, you can navigate to it. 若要指定應用程式流覽的第一個 Page,您需要設定啟動 PageTo specify the first Page that an application navigates to, you need to configure the start Page.

設定起始頁Configuring a Start Page

Xbap 需要在瀏覽器中裝載一定數量的應用程式基礎結構。XBAPs require a certain amount of application infrastructure to be hosted in a browser. 在 WPF 中,Application 類別是應用程式定義的一部分,可建立必要的應用程式基礎結構(請參閱應用程式管理總覽)。In WPF, the Application class is part of an application definition that establishes the required application infrastructure (see Application Management Overview).

應用程式定義通常會使用標記和程式碼後置來實作為,並將標記檔案設定為 MSBuildApplicationDefinition 專案。An application definition is usually implemented using both markup and code-behind, with the markup file configured as an MSBuildApplicationDefinition item. 以下是 XBAP 的應用程式定義。The following is an application definition for an XBAP.

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.App" />
using System.Windows;

namespace SDKSample
{
    public partial class App : Application { }
}

Imports System.Windows

Namespace SDKSample
    Partial Public Class App
        Inherits Application
    End Class
End Namespace

XBAP 可以使用其應用程式定義來指定開始 Page,也就是啟動 XBAP 時自動載入的 PageAn XBAP can use its application definition to specify a start Page, which is the Page that is automatically loaded when the XBAP is launched. 若要這麼做,您可以為所需的 Page設定具有統一資源識別元(URI)的 StartupUri 屬性。You do this by setting the StartupUri property with the uniform resource identifier (URI) for the desired Page.

注意

在大部分情況下,Page 會編譯成應用程式或與之一起部署。In most cases, the Page is either compiled into or deployed with an application. 在這些情況下,識別 Page 的 URI 是一個 pack URI,這是符合套件配置的 uri。In these cases, the URI that identifies a Page is a pack URI, which is a URI that conforms to the pack scheme. 套件 Uri 會在 WPF 的 Pack uri中進一步討論。Pack URIs are discussed further in Pack URIs in WPF. 您也可以巡覽至使用 http 配置的內容,後文會討論。You can also navigate to content using the http scheme, which is discussed below.

您可以在標記中以宣告方式設定 StartupUri,如下列範例所示。You can set StartupUri declaratively in markup, as shown in the following example.

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.App"
    StartupUri="PageWithHyperlink.xaml" />

在此範例中,StartupUri 屬性是以識別首頁的相對 pack URI 來設定。In this example, the StartupUri attribute is set with a relative pack URI that identifies HomePage.xaml. 當 XBAP 啟動時,首頁. xaml 會自動流覽並顯示。When the XBAP is launched, HomePage.xaml is automatically navigated to and displayed. 如下圖所示,它會顯示從 Web 服務器啟動的 XBAP。This is demonstrated by the following figure, which shows an XBAP that was launched from a Web server.

XBAP 頁面XBAP page

注意

如需有關開發和部署 Xbap 的詳細資訊,請參閱WPF XAML 瀏覽器應用程式總覽部署 wpf 應用程式For more information regarding the development and deployment of XBAPs, see WPF XAML Browser Applications Overview and Deploying a WPF Application.

設定主機視窗的標題、寬度和高度Configuring the Host Window's Title, Width, and Height

您在上圖中可能注意到的一件事,就是瀏覽器和索引標籤面板的標題都是 XBAP 的 URI。One thing you may have noticed from the previous figure is that the title of both the browser and the tab panel is the URI for the XBAP. 除了長之外,標題既不吸引人,也不提供資訊。Besides being long, the title is neither attractive nor informative. 基於這個理由,Page 提供了一種方式,可讓您藉由設定 WindowTitle 屬性來變更標題。For this reason, Page offers a way for you to change the title by setting the WindowTitle property. 此外,您可以分別設定 WindowWidthWindowHeight,以設定瀏覽器視窗的寬度和高度。Furthermore, you can configure the width and height of the browser window by setting WindowWidth and WindowHeight, respectively.

WindowTitleWindowWidthWindowHeight 可以在標記中以宣告方式設定,如下列範例所示。WindowTitle, WindowWidth, and WindowHeight can be set declaratively in markup, as shown in the following example.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.HomePage"
    WindowTitle="Page Title"
    WindowWidth="500"
    WindowHeight="200">
  Hello, from the XBAP HomePage!
</Page>

其結果如下圖所示。The result is shown in the following figure.

視窗標題、高度、寬度Window title, height, width

典型的 XBAP 包含數個頁面。A typical XBAP comprises several pages. 從一頁流覽至另一個頁面最簡單的方式,就是使用 HyperlinkThe simplest way to navigate from one page to another is to use a Hyperlink. 您可以使用 Hyperlink 元素,以宣告的方式將 Hyperlink 新增至 Page,如下列標記所示。You can declaratively add a Hyperlink to a Page by using the Hyperlink element, which is shown in the following markup.

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  WindowTitle="Page With Hyperlink"
  WindowWidth="250"
  WindowHeight="250">
<Hyperlink NavigateUri="UriOfPageToNavigateTo.xaml">
  Navigate to Another Page
</Hyperlink>
</Page>

Hyperlink 元素需要下列專案:A Hyperlink element requires the following:

  • 要導覽之 Page 的 pack URI,如 NavigateUri 屬性所指定。The pack URI of the Page to navigate to, as specified by the NavigateUri attribute.

  • 使用者可以按一下以起始導覽的內容,例如文字和影像(針對 Hyperlink 元素可以包含的內容,請參閱 Hyperlink)。Content that a user can click to initiate the navigation, such as text and images (for the content that the Hyperlink element can contain, see Hyperlink).

下圖顯示具有 HyperlinkPage 的 XBAP。The following figure shows an XBAP with a Page that has a Hyperlink.

具有超連結的頁面Page with Hyperlink

如您所預期,按一下 Hyperlink 會導致 XBAP 流覽至 NavigateUri 屬性所識別的 PageAs you would expect, clicking the Hyperlink causes the XBAP to navigate to the Page that is identified by the NavigateUri attribute. 此外,XBAP 會將先前 Page 的專案加入 Internet Explorer 的 [最近使用的頁面] 清單中。Additionally, the XBAP adds an entry for the previous Page to the Recent Pages list in Internet Explorer. 如下圖所示。This is shown in the following figure.

[上一頁] 和 [下一頁] 按鈕Back and Forward buttons

除了支援從一個 Page 導覽至另一個,Hyperlink 也支援片段導覽。As well as supporting navigation from one Page to another, Hyperlink also supports fragment navigation.

片段巡覽Fragment Navigation

片段導覽是目前 Page 或另一個 Page的內容片段導覽。Fragment navigation is the navigation to a content fragment in either the current Page or another Page. 在 WPF 中,內容片段是指已命名專案所包含的內容。In WPF, a content fragment is the content that is contained by a named element. 已命名的元素是已設定其 Name 屬性的元素。A named element is an element that has its Name attribute set. 下列標記顯示包含內容片段的已命名 TextBlock 元素。The following markup shows a named TextBlock element that contains a content fragment.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    WindowTitle="Page With Fragments" >
<!-- Content Fragment called "Fragment1" -->
<TextBlock Name="Fragment1">
  Ea vel dignissim te aliquam facilisis ...
</TextBlock>
</Page>

若要讓 Hyperlink 流覽至內容片段,NavigateUri 屬性必須包括下列各項:For a Hyperlink to navigate to a content fragment, the NavigateUri attribute must include the following:

  • 具有要導覽之內容片段的 Page URI。The URI of the Page with the content fragment to navigate to.

  • "#" 字元。A "#" character.

  • Page 上包含內容片段之元素的名稱。The name of the element on the Page that contains the content fragment.

片段 URI 具有下列格式。A fragment URI has the following format.

PageURI # ElementNamePageURI # ElementName

以下顯示的範例是設定為流覽至內容片段的 HyperlinkThe following shows an example of a Hyperlink that is configured to navigate to a content fragment.

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  WindowTitle="Page That Navigates To Fragment" >
<Hyperlink NavigateUri="PageWithFragments.xaml#Fragment1">
  Navigate To pack Fragment
</Hyperlink>
</Page>

注意

本節說明 WPF 中的預設片段導覽執行。This section describes the default fragment navigation implementation in WPF. WPF 也可以讓您實作為自己的片段導覽配置,而這種配置必須處理 NavigationService.FragmentNavigation 事件。WPF also allows you to implement your own fragment navigation scheme which, in part, requires handling the NavigationService.FragmentNavigation event.

重要

只有在可以透過 HTTP 流覽頁面時,您才可以導覽至鬆散 XAMLXAML 頁面中的片段(僅限標記的 XAMLXAML 檔案,其 Page 為根項目)。You can navigate to fragments in loose XAMLXAML pages (markup-only XAMLXAML files with Page as the root element) only if the pages can be browsed via HTTP.

不過,鬆散的 XAMLXAML 頁面可以流覽至它自己的片段。However, a loose XAMLXAML page can navigate to its own fragments.

雖然 Hyperlink 允許使用者起始特定 Page的導覽,但尋找和下載頁面的工作是由 NavigationService 類別執行。While Hyperlink allows a user to initiate navigation to a particular Page, the work of locating and downloading the page is performed by the NavigationService class. 基本上,NavigationService 提供代表用戶端程式代碼(例如 Hyperlink)處理導覽要求的功能。Essentially, NavigationService provides the ability to process a navigation request on behalf of client code, such as the Hyperlink. 此外,NavigationService 會執行追蹤和影響導覽要求的更高層級支援。Additionally, NavigationService implements higher-level support for tracking and influencing a navigation request.

按一下 Hyperlink 時,WPF 會呼叫 NavigationService.Navigate,以在指定的 pack URI 找出並下載 PageWhen a Hyperlink is clicked, WPF calls NavigationService.Navigate to locate and download the Page at the specified pack URI. 下載的 Page 會轉換成物件的樹狀結構,其根物件是已下載 Page的實例。The downloaded Page is converted to a tree of objects whose root object is an instance of the downloaded Page. Page 物件的參考會儲存在 NavigationService.Content 屬性中。A reference to the root Page object is stored in the NavigationService.Content property. 流覽至之內容的 pack URI 會儲存在 NavigationService.Source 屬性中,而 NavigationService.CurrentSource 會儲存流覽至之最後一頁的 pack URI。The pack URI for the content that was navigated to is stored in the NavigationService.Source property, while the NavigationService.CurrentSource stores the pack URI for the last page that was navigated to.

注意

WPF 應用程式可能會有一個以上的目前作用中 NavigationServiceIt is possible for a WPF application to have more than one currently active NavigationService. 如需詳細資訊,請參閱本主題稍後的導覽主機For more information, see Navigation Hosts later in this topic.

以程式設計的巡覽及巡覽服務Programmatic Navigation with the Navigation Service

如果使用 Hyperlink以宣告方式在標記中實作為導覽,您就不需要知道 NavigationService,因為 Hyperlink 會代表您使用 NavigationServiceYou don't need to know about NavigationService if navigation is implemented declaratively in markup using Hyperlink, because Hyperlink uses the NavigationService on your behalf. 這表示,只要 Hyperlink 的直接或間接父系是導覽主機(請參閱 [導覽主機]),Hyperlink 就能夠尋找和使用導覽主機的導覽服務來處理導覽要求。This means that, as long as either the direct or indirect parent of a Hyperlink is a navigation host (see Navigation Hosts), Hyperlink will be able to find and use the navigation host's navigation service to process a navigation request.

不過,在某些情況下,您需要直接使用 NavigationService,包括下列各項:However, there are situations when you need to use NavigationService directly, including the following:

  • 當您需要使用非無參數的函式來具現化 Page 時。When you need to instantiate a Page using a non-parameterless constructor.

  • 當您需要設定 Page 的屬性,然後再流覽至它。When you need to set properties on the Page before you navigate to it.

  • 當需要流覽的 Page 只能在執行時間決定。When the Page that needs to be navigated to can only be determined at run time.

在這些情況下,您需要撰寫程式碼,藉由呼叫 NavigationService 物件的 Navigate 方法,以程式設計方式起始導覽。In these situations, you need to write code to programmatically initiate navigation by calling the Navigate method of the NavigationService object. 這需要取得 NavigationService的參考。That requires getting a reference to a NavigationService.

取得 NavigationService 的參考Getting a Reference to the NavigationService

基於 [導覽主機] 區段中所述的原因,WPF 應用程式可以有多個 NavigationServiceFor reasons that are covered in the Navigation Hosts section, a WPF application can have more than one NavigationService. 這表示您的程式碼需要一種方式來尋找 NavigationService,這通常是流覽至目前 PageNavigationServiceThis means that your code needs a way to find a NavigationService, which is usually the NavigationService that navigated to the current Page. 您可以藉由呼叫 staticNavigationService.GetNavigationService 方法來取得 NavigationService 的參考。You can get a reference to a NavigationService by calling the staticNavigationService.GetNavigationService method. 若要取得導覽至特定 PageNavigationService,您可以將參考傳遞至 Page 做為 GetNavigationService 方法的引數。To get the NavigationService that navigated to a particular Page, you pass a reference to the Page as the argument of the GetNavigationService method. 下列程式碼顯示如何取得目前 PageNavigationServiceThe following code shows how to get the NavigationService for the current Page.

using System.Windows.Navigation;
// Get a reference to the NavigationService that navigated to this Page
NavigationService ns = NavigationService.GetNavigationService(this);
' Get a reference to the NavigationService that navigated to this Page
Dim ns As NavigationService = NavigationService.GetNavigationService(Me)

做為尋找 PageNavigationService 的快捷方式,Page 會執行 NavigationService 屬性。As a shortcut for finding the NavigationService for a Page, Page implements the NavigationService property. 這在下列範例中顯示。This is shown in the following example.

using System.Windows.Navigation;
// Get a reference to the NavigationService that navigated to this Page
NavigationService ns = this.NavigationService;
' Get a reference to the NavigationService that navigated to this Page
Dim ns As NavigationService = Me.NavigationService

注意

Page 引發 Loaded 事件時,Page 只能取得其 NavigationService 的參考。A Page can only get a reference to its NavigationService when Page raises the Loaded event.

以程式設計方式巡覽至頁面物件Programmatic Navigation to a Page Object

下列範例示範如何使用 NavigationService 以程式設計方式導覽至 PageThe following example shows how to use the NavigationService to programmatically navigate to a Page. 必須以程式設計方式導覽,因為所流覽的 Page 只能使用單一、非參數的函式來具現化。Programmatic navigation is required because the Page that is being navigated to can only be instantiated using a single, non-parameterless constructor. 具有非無參數的函式的 Page 會顯示在下列標記和程式碼中。The Page with the non-parameterless constructor is shown in the following markup and code.

<Page
    x:Class="SDKSample.PageWithNonDefaultConstructor"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="PageWithNonDefaultConstructor">
  
  <!-- Content goes here -->
  
</Page>
using System.Windows.Controls;

namespace SDKSample
{
    public partial class PageWithNonDefaultConstructor : Page
    {
        public PageWithNonDefaultConstructor(string message)
        {
            InitializeComponent();

            this.Content = message;
        }
    }
}

Namespace SDKSample
    Partial Public Class PageWithNonDefaultConstructor
        Inherits Page
        Public Sub New(ByVal message As String)
            InitializeComponent()

            Me.Content = message
        End Sub
    End Class
End Namespace

使用非無參數的函式流覽至 PagePage 會顯示在下列標記和程式碼中。The Page that navigates to the Page with the non-parameterless constructor is shown in the following markup and code.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.NSNavigationPage">

  <Hyperlink Click="hyperlink_Click">
    Navigate to Page with Non-Default Constructor
  </Hyperlink>

</Page>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace SDKSample
{
    public partial class NSNavigationPage : Page
    {
        public NSNavigationPage()
        {
            InitializeComponent();
        }

        void hyperlink_Click(object sender, RoutedEventArgs e)
        {
            // Instantiate the page to navigate to
            PageWithNonDefaultConstructor page = new PageWithNonDefaultConstructor("Hello!");

            // Navigate to the page, using the NavigationService
            this.NavigationService.Navigate(page);
        }
    }
}

Namespace SDKSample
    Partial Public Class NSNavigationPage
        Inherits Page
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub hyperlink_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            ' Instantiate the page to navigate to
            Dim page As New PageWithNonDefaultConstructor("Hello!")

            ' Navigate to the page, using the NavigationService
            Me.NavigationService.Navigate(page)
        End Sub
    End Class
End Namespace

按一下此 Page 上的 Hyperlink 時,就會藉由具現化 Page 來起始導覽,以使用非無參數的函式並呼叫 NavigationService.Navigate 方法來流覽至。When the Hyperlink on this Page is clicked, navigation is initiated by instantiating the Page to navigate to using the non-parameterless constructor and calling the NavigationService.Navigate method. Navigate 接受 NavigationService 將導覽至之物件的參考,而不是套件 URI。Navigate accepts a reference to the object that the NavigationService will navigate to, rather than a pack URI.

以程式設計的巡覽及 Pack URIProgrammatic Navigation with a Pack URI

如果您需要以程式設計方式來建立 pack URI (例如,您只能在執行時間判斷 pack URI),可以使用 NavigationService.Navigate 方法。If you need to construct a pack URI programmatically (when you can only determine the pack URI at run time, for example), you can use the NavigationService.Navigate method. 這在下列範例中顯示。This is shown in the following example.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.NSUriNavigationPage">
  <Hyperlink Click="hyperlink_Click">Navigate to Page by Pack URI</Hyperlink>
</Page>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace SDKSample
{
    public partial class NSUriNavigationPage : Page
    {
        public NSUriNavigationPage()
        {
            InitializeComponent();
        }

        void hyperlink_Click(object sender, RoutedEventArgs e)
        {
            // Create a pack URI
            Uri uri = new Uri("AnotherPage.xaml", UriKind.Relative);

            // Get the navigation service that was used to
            // navigate to this page, and navigate to
            // AnotherPage.xaml
            this.NavigationService.Navigate(uri);
        }
    }
}

Namespace SDKSample
    Partial Public Class NSUriNavigationPage
        Inherits Page
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub hyperlink_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            ' Create a pack URI
            Dim uri As New Uri("AnotherPage.xaml", UriKind.Relative)

            ' Get the navigation service that was used to 
            ' navigate to this page, and navigate to 
            ' AnotherPage.xaml
            Me.NavigationService.Navigate(uri)
        End Sub
    End Class
End Namespace

重新整理目前的頁面Refreshing the Current Page

如果 Page 的 pack URI 與儲存在 NavigationService.Source 屬性中的 pack URI 相同,則不會下載。A Page is not downloaded if it has the same pack URI as the pack URI that is stored in the NavigationService.Source property. 若要強制 WPF 再次下載目前的頁面,您可以呼叫 NavigationService.Refresh 方法,如下列範例所示。To force WPF to download the current page again, you can call the NavigationService.Refresh method, as shown in the following example.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.NSRefreshNavigationPage">
 <Hyperlink Click="hyperlink_Click">Refresh this page</Hyperlink>
</Page>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace SDKSample
{
    public partial class NSRefreshNavigationPage : Page
    {

Namespace SDKSample
    Partial Public Class NSRefreshNavigationPage
        Inherits Page
        void hyperlink_Click(object sender, RoutedEventArgs e)
        {
            // Force WPF to download this page again
            this.NavigationService.Refresh();
        }
    }
}
        Private Sub hyperlink_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            ' Force WPF to download this page again
            Me.NavigationService.Refresh()
        End Sub
    End Class
End Namespace

如您所見,有多種方式可以初始化巡覽。There are many ways to initiate navigation, as you've seen. 當導覽已起始,而且導覽正在進行時,您可以使用 NavigationService所實作為的下列事件來追蹤和影響導覽:When navigation is initiated, and while navigation is in progress, you can track and influence the navigation using the following events that are implemented by NavigationService:

  • NavigatingNavigating. 要求新的巡覽時發生。Occurs when a new navigation is requested. 可用於取消巡覽。Can be used to cancel the navigation.

  • NavigationProgressNavigationProgress. 在下載期間定期發生以提供導覽進度資訊。Occurs periodically during a download to provide navigation progress information.

  • NavigatedNavigated. 找到並下載頁面時發生。Occurs when the page has been located and downloaded.

  • NavigationStoppedNavigationStopped. 當導覽停止(藉由呼叫 StopLoading)時發生,或在目前的導覽正在進行中要求新的流覽時,就會發生。Occurs when the navigation is stopped (by calling StopLoading), or when a new navigation is requested while a current navigation is in progress.

  • NavigationFailedNavigationFailed. 在廵覽至要求的內容引發錯誤時發生。Occurs when an error is raised while navigating to the requested content.

  • LoadCompletedLoadCompleted. 當載入並剖析巡覽到的內容,且開始轉譯時發生。Occurs when content that was navigated to is loaded and parsed, and has begun rendering.

  • FragmentNavigationFragmentNavigation. 當內容片段巡覽開始時發生,狀況為︰Occurs when navigation to a content fragment begins, which happens:

    • 立即發生,如果所需片段位在目前的內容中。Immediately, if the desired fragment is in the current content.

    • 載入來源內容之後,如果所需片段位在不同的內容中。After the source content has been loaded, if the desired fragment is in different content.

下圖顯示巡覽事件的引發順序。The navigation events are raised in the order that is illustrated by the following figure.

頁面導覽流程圖Page navigation flow chart

一般來說,Page 並不在意這些事件。In general, a Page isn't concerned about these events. 應用程式很有可能會擔心它們,因此,這些事件也會由 Application 類別引發:It is more likely that an application is concerned with them and, for that reason, these events are also raised by the Application class:

每次 NavigationService 引發事件時,Application 類別都會引發對應的事件。Every time NavigationService raises an event, the Application class raises the corresponding event. FrameNavigationWindow 提供相同的事件,以偵測其各自範圍內的導覽。Frame and NavigationWindow offer the same events to detect navigation within their respective scopes.

在某些情況下,Page 可能會對這些事件感興趣。In some cases, a Page might be interested in these events. 例如,Page 可能會處理 NavigationService.Navigating 事件,以判斷是否要取消本身的導覽。For example, a Page might handle the NavigationService.Navigating event to determine whether or not to cancel navigation away from itself. 這在下列範例中顯示。This is shown in the following example.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.CancelNavigationPage">
  <Button Click="button_Click">Navigate to Another Page</Button>
</Page>
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;

namespace SDKSample
{
    public partial class CancelNavigationPage : Page
    {
        public CancelNavigationPage()
        {
            InitializeComponent();

            // Can only access the NavigationService when the page has been loaded
            this.Loaded += new RoutedEventHandler(CancelNavigationPage_Loaded);
            this.Unloaded += new RoutedEventHandler(CancelNavigationPage_Unloaded);
        }

        void button_Click(object sender, RoutedEventArgs e)
        {
            // Force WPF to download this page again
            this.NavigationService.Navigate(new Uri("AnotherPage.xaml", UriKind.Relative));
        }

        void CancelNavigationPage_Loaded(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigating += new NavigatingCancelEventHandler(NavigationService_Navigating);
        }

        void CancelNavigationPage_Unloaded(object sender, RoutedEventArgs e)
        {
            this.NavigationService.Navigating -= new NavigatingCancelEventHandler(NavigationService_Navigating);
        }

        void NavigationService_Navigating(object sender, NavigatingCancelEventArgs e)
        {
            // Does the user really want to navigate to another page?
            MessageBoxResult result;
            result = MessageBox.Show("Do you want to leave this page?", "Navigation Request", MessageBoxButton.YesNo);

            // If the user doesn't want to navigate away, cancel the navigation
            if (result == MessageBoxResult.No) e.Cancel = true;
        }
    }
}

Namespace SDKSample
    Partial Public Class CancelNavigationPage
        Inherits Page
        Public Sub New()
            InitializeComponent()

            ' Can only access the NavigationService when the page has been loaded
            AddHandler Loaded, AddressOf CancelNavigationPage_Loaded
            AddHandler Unloaded, AddressOf CancelNavigationPage_Unloaded
        End Sub

        Private Sub button_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            ' Force WPF to download this page again
            Me.NavigationService.Navigate(New Uri("AnotherPage.xaml", UriKind.Relative))
        End Sub

        Private Sub CancelNavigationPage_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
            AddHandler NavigationService.Navigating, AddressOf NavigationService_Navigating
        End Sub

        Private Sub CancelNavigationPage_Unloaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
            RemoveHandler NavigationService.Navigating, AddressOf NavigationService_Navigating
        End Sub

        Private Sub NavigationService_Navigating(ByVal sender As Object, ByVal e As NavigatingCancelEventArgs)
            ' Does the user really want to navigate to another page?
            Dim result As MessageBoxResult
            result = MessageBox.Show("Do you want to leave this page?", "Navigation Request", MessageBoxButton.YesNo)

            ' If the user doesn't want to navigate away, cancel the navigation
            If result = MessageBoxResult.No Then
                e.Cancel = True
            End If
        End Sub
    End Class
End Namespace

如果您向 Page註冊具有導覽事件的處理常式,如上述範例所示,您也必須取消註冊事件處理常式。If you register a handler with a navigation event from a Page, as the preceding example does, you must also unregister the event handler. 如果您沒有這麼做,可能會有關于 WPF 導覽如何使用日誌來記住 Page 導覽的副作用。If you don't, there may be side effects with respect to how WPF navigation remembers Page navigation using the journal.

以日誌記憶巡覽Remembering Navigation with the Journal

WPF 會使用兩個堆疊來記住您所流覽的頁面:後端堆疊和向前堆疊。WPF uses two stacks to remember the pages that you have navigated from: a back stack and a forward stack. 當您從目前的 Page 導覽至新 Page 或轉送到現有的 Page時,目前的 Page 會加入至後端堆疊When you navigate from the current Page to a new Page or forward to an existing Page, the current Page is added to the back stack. 當您從目前的 Page 流覽回到先前的 Page時,會將目前的 Page 新增至向前堆疊When you navigate from the current Page back to the previous Page, the current Page is added to the forward stack. 上一頁堆疊、下一頁堆疊和管理它們的功能,統稱為日誌。The back stack, the forward stack, and the functionality to manage them, are collectively referred to as the journal. 後端堆疊和向前堆疊中的每個專案都是 JournalEntry 類別的實例,而則稱為日誌項目Each item in the back stack and the forward stack is an instance of the JournalEntry class, and is referred to as a journal entry.

就概念而言,日誌的運作方式與 Internet Explorer 中的 [上一頁] 和 [下一頁] 按鈕相同。Conceptually, the journal operates the same way that the Back and Forward buttons in Internet Explorer do. 如下圖所示。These are shown in the following figure.

[上一頁] 和 [下一頁] 按鈕Back and Forward buttons

若為 Internet Explorer 所裝載的 Xbap,WPF 會將日誌整合到 Internet Explorer 的導覽 UIUIFor XBAPs that are hosted by Internet Explorer, WPF integrates the journal into the navigation UIUI of Internet Explorer. 這可讓使用者使用 Internet Explorer 中的 [上一頁]、[下一頁] 和 [最近使用的頁面] 按鈕,流覽 XBAP 中的頁面。This allows users to navigate pages in an XBAP by using the Back, Forward, and Recent Pages buttons in Internet Explorer.

重要

在 Internet Explorer 中,當使用者離開並回到 XBAP 時,只有未保持運作之頁面的記錄項目會保留在日誌中。In Internet Explorer, when a user navigates away from and back to an XBAP, only the journal entries for pages that were not kept alive are retained in the journal. 如需讓頁面保持運作的討論,請參閱本主題稍後的頁面存留期和日誌For discussion on keeping pages alive, see Page Lifetime and the Journal later in this topic.

根據預設,Internet Explorer [最近使用的頁面] 清單中出現的每個 Page 文字,都是 Page的 URI。By default, the text for each Page that appears in the Recent Pages list of Internet Explorer is the URI for the Page. 在許多情況下,這對使用者都不是特別有意義。In many cases, this is not particularly meaningful to the user. 幸運的是,您可以變更使用下列選項之一的文字︰Fortunately, you can change the text using one the following options:

  1. 附加的 JournalEntry.Name 屬性值。The attached JournalEntry.Name attribute value.

  2. Page.Title 屬性值。The Page.Title attribute value.

  3. Page.WindowTitle 屬性值和目前 Page的 URI。The Page.WindowTitle attribute value and the URI for the current Page.

  4. 目前 Page的 URI。The URI for the current Page. (預設)(Default)

選項列示順序符合尋找文字的優先順序。The order in which the options are listed matches the order of precedence for finding the text. 例如,如果已設定 JournalEntry.Name,則會忽略其他值。For example, if JournalEntry.Name is set, the other values are ignored.

下列範例會使用 Page.Title 屬性來變更日誌項目所顯示的文字。The following example uses the Page.Title attribute to change the text that appears for a journal entry.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.PageWithTitle"
    Title="This is the title of the journal entry for this page.">
</Page>
using System.Windows.Controls;

namespace SDKSample
{
    public partial class PageWithTitle : Page
    {

Namespace SDKSample
    Partial Public Class PageWithTitle
        Inherits Page
    }
}
    End Class
End Namespace

雖然使用者可以使用 Internet Explorer 中的 [上一頁]、[下一頁] 和 [最近] 頁面來流覽日誌,但是您也可以使用 WPF 所提供的宣告式和程式設計機制來流覽日誌。Although a user can navigate the journal by using the Back, Forward, and Recent Pages in Internet Explorer, you can also navigate the journal using both declarative and programmatic mechanisms provided by WPF. 這麼做的其中一個原因是在您的頁面中提供自訂的導覽 Ui。One reason to do this is to provide custom navigation UIs in your pages.

您可以使用 NavigationCommands所公開的導覽命令,以宣告方式新增日誌流覽支援。You can declaratively add journal navigation support by using the navigation commands exposed by NavigationCommands. 下列範例示範如何使用 BrowseBack 導覽命令。The following example demonstrates how to use the BrowseBack navigation command.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.NavigationCommandsPage">
<Hyperlink Command="NavigationCommands.BrowseBack">Back</Hyperlink>
<Hyperlink Command="NavigationCommands.BrowseForward">Forward</Hyperlink>
</Page>

您可以使用 NavigationService 類別的下列其中一個成員,以程式設計方式導覽日誌:You can programmatically navigate the journal by using one of the following members of the NavigationService class:

您也可以透過程式設計方式動作記錄,如本主題稍後的保留內容狀態與導覽歷程記錄中所述。The journal can also be manipulated programmatically, as discussed in Retaining Content State with Navigation History later in this topic.

網頁存留期和日誌Page Lifetime and the Journal

假設有多個頁面包含豐富內容的 XBAP,包括圖形、動畫和媒體。Consider an XBAP with several pages that contain rich content, including graphics, animations, and media. 這類頁面的磁碟使用量可能相當大,尤其是使用視訊和音訊媒體的時候。The memory footprint for pages like these could be quite large, particularly if video and audio media are used. 假設筆記本「記憶」已流覽過的頁面,這樣的 XBAP 可能很快就會耗用大量且明顯的記憶體數量。Given that the journal "remembers" pages that have been navigated to, such an XBAP could quickly consume a large and noticeable amount of memory.

基於這個理由,日誌的預設行為是將 Page 中繼資料儲存在每個日誌項目中,而不是 Page 物件的參考。For this reason, the default behavior of the journal is to store Page metadata in each journal entry rather than a reference to a Page object. 當流覽記錄項目時,其 Page 中繼資料會用來建立指定 Page的新實例。When a journal entry is navigated to, its Page metadata is used to create a new instance of the specified Page. 因此,流覽的每個 Page 都具有下圖所說明的存留期。As a consequence, each Page that is navigated has the lifetime that is illustrated by the following figure.

頁面存留期Page lifetime

雖然使用預設日誌行為可以節省記憶體耗用量,但每頁轉譯的效能可能會降低;reinstantiating Page 可能需要大量時間,特別是當它有許多內容時。Although using the default journaling behavior can save on memory consumption, per-page rendering performance might be reduced; reinstantiating a Page can be time-intensive, particularly if it has a lot of content. 如果您需要將 Page 實例保留在日誌中,您可以使用兩種技術來進行繪製。If you need to retain a Page instance in the journal, you can draw on two techniques for doing so. 首先,您可以藉由呼叫 NavigationService.Navigate 方法,以程式設計方式流覽至 Page 物件。First, you can programmatically navigate to a Page object by calling the NavigationService.Navigate method.

第二,您可以藉由將 KeepAlive 屬性設定為 true (預設值為 false),指定 WPF 保留日誌中 Page 的實例。Second, you can specify that WPF retain an instance of a Page in the journal by setting the KeepAlive property to true (the default is false). 如下列範例所示,您可以在標記中以宣告方式設定 KeepAliveAs shown in the following example, you can set KeepAlive declaratively in markup.

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.KeepAlivePage"
    KeepAlive="True">
  
  An instance of this page is stored in the journal.
  
</Page>

保持運作之 Page 的存留期間,與不會有任何差別。The lifetime of a Page that is kept alive is subtly different from one that is not. 第一次流覽至保持運作的 Page 時,它會具現化,就像未保持運作的 Page 一樣。The first time a Page that is kept alive is navigated to, it is instantiated just like a Page that is not kept alive. 不過,因為 Page 的實例會保留在日誌中,所以只要它保留在日誌中,它就不會再次具現化。However, because an instance of the Page is retained in the journal, it is never instantiated again for as long as it remains in the journal. 因此,如果 Page 具有必須在每次流覽 Page 時呼叫的初始化邏輯,您應該將它從該函式移至 Loaded 事件的處理常式。Consequently, if a Page has initialization logic that needs to be called every time the Page is navigated to, you should move it from the constructor into a handler for the Loaded event. 如下圖所示,LoadedUnloaded 事件仍會在每次流覽和繼承 Page 時引發。As shown in the following figure, the Loaded and Unloaded events are still raised each time a Page is navigated to and from, respectively.

當已載入和卸載的事件引發時When the Loaded and Unloaded events are raised

Page 未保持運作時,您不應該執行下列其中一項動作:When a Page is not kept alive, you should not do either of the following:

  • 儲存其參考或任何部分。Store a reference to it, or any part of it.

  • 使用它未實作的事件來登錄事件處理常式。Register event handlers with events that are not implemented by it.

執行其中一項作業會建立參考,強制將 Page 保留在記憶體中,即使已從日誌中移除亦然。Doing either of these will create references that force the Page to be retained in memory, even after it has been removed from the journal.

一般來說,您應該偏好預設的 Page 行為,而不讓 Page 保持運作。In general, you should prefer the default Page behavior of not keeping a Page alive. 不過,這有下一節要討論的隱含狀態。However, this has state implications that are discussed in the next section.

以巡覽記錄保留內容狀態Retaining Content State with Navigation History

如果 Page 未保持運作,而且它具有可從使用者收集資料的控制項,則如果使用者流覽離開並回到 Page,資料會發生什麼事?If a Page is not kept alive, and it has controls that collect data from the user, what happens to the data if a user navigates away from and back to the Page? 從使用者體驗的觀點而言,使用者應該會希望看到他們先前所輸入的資料。From a user experience perspective, the user should expect to see the data they entered previously. 可惜的是,因為每個導覽都會建立 Page 的新實例,所以會 reinstantiated 收集資料的控制項並遺失資料。Unfortunately, because a new instance of the Page is created with each navigation, the controls that collected the data are reinstantiated and the data is lost.

幸運的是,日誌可支援在 Page 的導覽中記住資料,包括控制資料。Fortunately, the journal provides support for remembering data across Page navigations, including control data. 具體而言,每個 Page 的日誌項目會作為相關聯 Page 狀態的暫存容器。Specifically, the journal entry for each Page acts as a temporary container for the associated Page state. 下列步驟概述從流覽 Page 時,如何使用這項支援:The following steps outline how this support is used when a Page is navigated from:

  1. 目前 Page 的專案會新增至日誌。An entry for the current Page is added to the journal.

  2. Page 的狀態會與該頁面的日誌項目一起儲存,並新增到後端堆疊中。The state of the Page is stored with the journal entry for that page, which is added to the back stack.

  3. 新的 Page 會被流覽至。The new Page is navigated to.

當頁面 Page 導覽至時,使用日誌,會進行下列步驟:When the page Page is navigated back to, using the journal, the following steps take place:

  1. Page (後端堆疊上的前幾個日誌項目)已具現化。The Page (the top journal entry on the back stack) is instantiated.

  2. Page 會以 Page的日誌項目所儲存的狀態重新整理。The Page is refreshed with the state that was stored with the journal entry for the Page.

  3. Page 會流覽回。The Page is navigated back to.

當下列控制項用於 Page時,WPF 會自動使用這項支援:WPF automatically uses this support when the following controls are used on a Page:

如果 Page 使用這些控制項,則會在 Page 導覽中記住輸入的資料,如同下圖中的 [我的最愛ListBox 色彩] 所示。If a Page uses these controls, data entered into them is remembered across Page navigations, as demonstrated by the Favorite ColorListBox in the following figure.

具有記憶狀態之控制項的頁面Page with controls that remember state

Page 擁有上述清單以外的控制項,或當狀態儲存在自訂物件中時,您必須撰寫程式碼,讓日誌在 Page 導覽之間記住狀態。When a Page has controls other than those in the preceding list, or when state is stored in custom objects, you need to write code to cause the journal to remember state across Page navigations.

如果您需要記住 Page 導覽間的小部分狀態,您可以使用以 FrameworkPropertyMetadata.Journal 中繼資料旗標設定的相依性屬性(請參閱 DependencyProperty)。If you need to remember small pieces of state across Page navigations, you can use dependency properties (see DependencyProperty) that are configured with the FrameworkPropertyMetadata.Journal metadata flag.

如果您的 Page 需要記住的狀態包含多個資料片段,您可能會發現在單一類別中封裝您的狀態並執行 IProvideCustomContentState 介面的程式碼較少。If the state that your Page needs to remember across navigations comprises multiple pieces of data, you may find it less code intensive to encapsulate your state in a single class and implement the IProvideCustomContentState interface.

如果您需要流覽單一 Page的各種狀態,而不是從 Page 本身流覽,您可以使用 IProvideCustomContentStateNavigationService.AddBackEntryIf you need to navigate through various states of a single Page, without navigating from the Page itself, you can use IProvideCustomContentState and NavigationService.AddBackEntry.

CookiesCookies

WPF 應用程式可以儲存資料的另一種方式是使用 SetCookieGetCookie 方法來建立、更新和刪除 cookie。Another way that WPF applications can store data is with cookies, which are created, updated, and deleted by using the SetCookie and GetCookie methods. 您可以在 WPF 中建立的 cookie 與其他類型的 Web 應用程式所使用的 cookie 相同。cookie 是應用程式在應用程式會話期間或之間儲存的任意資料片段。The cookies that you can create in WPF are the same cookies that other types of Web applications use; cookies are arbitrary pieces of data that are stored by an application on a client machine either during or across application sessions. Cookie 資料通常會採用下列格式的名稱/值組形式。Cookie data typically takes the form of a name/value pair in the following format.

名稱=Name = Value

當資料傳遞至 SetCookie,以及應設定 cookie 的位置 Uri 時,就會在記憶體中建立 cookie,而且僅適用于目前應用程式會話的持續時間。When the data is passed to SetCookie, along with the Uri of the location for which the cookie should be set, a cookie is created in-memory, and it is only available for the duration of the current application session. 這種類型的 cookie 稱為會話 cookieThis type of cookie is referred to as a session cookie.

若要在應用程式工作階段之間儲存 Cookie,到期日必須使用下列格式新增至 Cookie。To store a cookie across application sessions, an expiration date must be added to the cookie, using the following format.

名稱=; expires=DAY, DD-MMM-YYYY HH:MM:SS GMTNAME = VALUE ; expires=DAY, DD-MMM-YYYY HH:MM:SS GMT

具有到期日的 cookie 會儲存在目前 Windows 安裝的 [Internet Files] 資料夾中,直到 cookie 到期為止。A cookie with an expiration date is stored in the current Windows installation's Temporary Internet Files folder until the cookie expires. 這類 cookie 稱為持續性 cookie ,因為它會在應用程式會話之間持續保存。Such a cookie is known as a persistent cookie because it persists across application sessions.

您可以藉由呼叫 GetCookie 方法,傳遞 cookie 使用 SetCookie 方法設定的位置 Uri,來抓取會話和持續性 cookie。You retrieve both session and persistent cookies by calling the GetCookie method, passing the Uri of the location where the cookie was set with the SetCookie method.

以下是 WPF 支援 cookie 的一些方式:The following are some of the ways that cookies are supported in WPF:

  • WPF 獨立應用程式和 Xbap 可以建立和管理 cookie。WPF standalone applications and XBAPs can both create and manage cookies.

  • 您可以從瀏覽器存取 XBAP 所建立的 cookie。Cookies that are created by an XBAP can be accessed from the browser.

  • 來自相同網域的 Xbap 可以建立和共用 cookie。XBAPs from the same domain can create and share cookies.

  • 來自相同網域的 Xbap 和 HTML 頁面可以建立和共用 cookie。XBAPs and HTML pages from the same domain can create and share cookies.

  • 當 Xbap 和鬆散的 XAMLXAML 頁面提出 Web 要求時,會分派 cookie。Cookies are dispatched when XBAPs and loose XAMLXAML pages make Web requests.

  • 在 IFRAME 中裝載的頂層 Xbap 和 Xbap 都可以存取 cookie。Both top-level XBAPs and XBAPs hosted in IFRAMES can access cookies.

  • WPF 中的 Cookie 支援對所有支援的瀏覽器都是相同的。Cookie support in WPF is the same for all supported browsers.

  • 在 Internet Explorer 中,適用于 cookie 的 P3P 原則會由 WPF 接受,特別是關於第一方和協力廠商的 Xbap。In Internet Explorer, P3P policy that pertains to cookies is honored by WPF, particularly with respect to first-party and third-party XBAPs.

結構化巡覽Structured Navigation

如果您需要將資料從一個 Page 傳遞至另一個,您可以將資料當做引數傳遞至 Page的非無參數的函式。If you need to pass data from one Page to another, you can pass the data as arguments to a non-parameterless constructor of the Page. 請注意,如果您使用這項技術,就必須讓 Page 保持運作;如果不是,則當您下次流覽至 Page時,WPF 會使用無參數的函式來 reinstantiates PageNote that if you use this technique, you must keep the Page alive; if not, the next time you navigate to the Page, WPF reinstantiates the Page by using the parameterless constructor.

或者,您的 Page 可以執行使用需要傳遞的資料所設定的屬性。Alternatively, your Page can implement properties that are set with the data that needs to be passed. 不過,當 Page 需要將資料傳回給導覽到它的 Page 時,就會變得很棘手。Things become tricky, however, when a Page needs to pass data back to the Page that navigated to it. 問題在於,導覽原本並不支援機制,以確保在流覽之後,會將 Page 傳回給。The problem is that navigation doesn't natively support mechanisms for guaranteeing that a Page will be returned to after it is navigated from. 基本上,巡覽不支援呼叫/傳回語意。Essentially, navigation doesn't support call/return semantics. 為了解決這個問題,WPF 提供了 PageFunction<T> 類別,您可以用它來確保 Page 以可預測且結構化的方式傳回至。To solve this problem, WPF provides the PageFunction<T> class that you can use to ensure that a Page is returned to in a predictable and structured fashion. 如需詳細資訊,請參閱結構化導覽總覽For more information, see Structured Navigation Overview.

NavigationWindow 類別The NavigationWindow Class

至此,您已了解最可能用來建置有可巡覽內容之應用程式的巡覽服務範圍。To this point, you've seen the gamut of navigation services that you are most likely to use to build applications with navigable content. 這些服務是在 Xbap 的內容中討論,雖然它們不限於 Xbap。These services were discussed in the context of XBAPs, although they are not limited to XBAPs. 新式作業系統和 Windows 應用程式利用新式使用者的瀏覽器體驗,將瀏覽器樣式的導覽併入獨立應用程式中。Modern operating systems and Windows applications take advantage of the browser experience of modern users to incorporate browser-style navigation into standalone applications. 常見範例包括︰Common examples include:

  • 文字同義字︰巡覽文字選擇。Word Thesaurus: Navigate word choices.

  • 檔案總管︰巡覽檔案和資料夾。File Explorer: Navigate files and folders.

  • 精靈︰將複雜的工作細分成可往來巡覽的多個頁面。Wizards: Breaking down a complex task into multiple pages that can be navigated between. 其中一個範例是處理新增和移除 Windows 功能的 Windows 元件 Wizard。An example is the Windows Components Wizard that handles adding and removing Windows features.

若要將瀏覽器樣式的導覽併入您的獨立應用程式,您可以使用 NavigationWindow 類別。To incorporate browser-style navigation into your standalone applications, you can use the NavigationWindow class. NavigationWindow 衍生自 Window,並使用 Xbap 所提供的相同導覽支援來加以擴充。NavigationWindow derives from Window and extends it with the same support for navigation that XBAPs provide. 您可以使用 NavigationWindow 做為獨立應用程式的主視窗,或當做對話方塊之類的次要視窗。You can use NavigationWindow as either the main window of your standalone application or as a secondary window such as a dialog box.

若要執行 NavigationWindow,如同 WPF 中的大部分最上層類別(WindowPage等等),您可以使用標記和程式碼後置的組合。To implement a NavigationWindow, as with most top-level classes in WPF (Window, Page, and so on), you use a combination of markup and code-behind. 這在下列範例中顯示。This is shown in the following example.

<NavigationWindow
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.MainWindow" 
    Source="HomePage.xaml"/>
using System.Windows.Navigation;

namespace SDKSample
{
    public partial class MainWindow : NavigationWindow
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }
}

Namespace SDKSample
    Partial Public Class MainWindow
        Inherits NavigationWindow
        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace

此程式碼會建立 NavigationWindow,以在 NavigationWindow 開啟時,自動流覽至 Page (首頁. xaml)。This code creates a NavigationWindow that automatically navigates to a Page (HomePage.xaml) when the NavigationWindow is opened. 如果 NavigationWindow 是主應用程式視窗,您可以使用 StartupUri 屬性來啟動它。If the NavigationWindow is the main application window, you can use the StartupUri attribute to launch it. 下列標記顯示此做法。This is shown in the following markup.

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    StartupUri="MainWindow.xaml" />

下圖顯示 NavigationWindow 做為獨立應用程式的主視窗。The following figure shows the NavigationWindow as the main window of a standalone application.

主視窗A main window

從圖中,您可以看到 NavigationWindow 有一個標題,即使它並未設定在上述範例的 NavigationWindow 實程式碼中也一樣。From the figure, you can see that the NavigationWindow has a title, even though it wasn't set in the NavigationWindow implementation code from the preceding example. 而是使用 [WindowTitle] 屬性來設定標題,如下列程式碼所示。Instead, the title is set using the WindowTitle property, which is shown in the following code.

<Page 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    Title="Home Page"
    WindowTitle="NavigationWindow">
</Page>

設定 WindowWidthWindowHeight 屬性也會影響 NavigationWindowSetting the WindowWidth and WindowHeight properties also affects the NavigationWindow.

當您需要自訂其行為或其外觀時,通常會執行自己的 NavigationWindowUsually, you implement your own NavigationWindow when you need to customize either its behavior or its appearance. 如果兩樣都不做,您可以使用捷徑。If you do neither, you can use a shortcut. 如果您在獨立應用程式中將 Page 的 pack URI 指定為 StartupUriApplication 會自動建立 NavigationWindow 來裝載 PageIf you specify the pack URI of a Page as the StartupUri in a standalone application, Application automatically creates a NavigationWindow to host the Page. 下列標記顯示如何啟用此功能。The following markup shows how to enable this.

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    StartupUri="HomePage.xaml" />

如果您想要讓一個次要應用程式視窗(例如對話方塊)成為 NavigationWindow,您可以使用下列範例中的程式碼來開啟它。If you want a secondary application window such as a dialog box to be a NavigationWindow, you can use the code in the following example to open it.

// Open a navigation window as a dialog box
NavigationWindowDialogBox dlg = new NavigationWindowDialogBox();
dlg.Source = new Uri("HomePage.xaml", UriKind.Relative);
dlg.Owner = this;
dlg.ShowDialog();
' Open a navigation window as a dialog box
Dim dlg As New NavigationWindowDialogBox()
dlg.Source = New Uri("HomePage.xaml", UriKind.Relative)
dlg.Owner = Me
dlg.ShowDialog()

其結果如下圖所示。The following figure shows the result.

對話方塊A dialog box

如您所見,NavigationWindow 會顯示 Internet Explorer 樣式的 [上一頁] 和 [下一頁] 按鈕,讓使用者可以流覽日誌。As you can see, NavigationWindow displays Internet Explorer-style Back and Forward buttons that allow users to navigate the journal. 這些按鈕提供相同的使用者體驗,如下圖所示。These buttons provide the same user experience, as shown in the following figure.

NavigationWindow 中的 [上一頁] 和 [下一頁] 按鈕Back and Forward buttons in a NavigationWindow

如果您的頁面提供自己的日誌流覽支援和 UI,您可以將 [ShowsNavigationUI] 屬性的值設定為 [false],以隱藏 NavigationWindow 顯示的 [上一頁] 和 [下一頁] 按鈕。If your pages provide their own journal navigation support and UI, you can hide the Back and Forward buttons displayed by NavigationWindow by setting the value of the ShowsNavigationUI property to false.

或者,您可以使用 WPF 中的自訂支援來取代 NavigationWindow 本身的 UIUIAlternatively, you can use customization support in WPF to replace the UIUI of the NavigationWindow itself.

Frame 類別The Frame Class

瀏覽器和 NavigationWindow 都是裝載可流覽內容的視窗。Both the browser and NavigationWindow are windows that host navigable content. 在某些情況下,應用程式會有不需要由整個視窗裝載的內容。In some cases, applications have content that does not need to be hosted by an entire window. 這類內容反可以裝載於其他內容中。Instead, such content be hosted inside other content. 您可以使用 Frame 類別,將可流覽的內容插入至其他內容。You can insert navigable content into other content by using the Frame class. Frame 提供與 NavigationWindow 和 Xbap 相同的支援。Frame provides the same support as NavigationWindow and XBAPs.

下列範例示範如何使用 Frame 元素,以宣告方式將 Frame 加入 PageThe following example shows how to add a Frame to a Page declaratively by using the Frame element.

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  WindowTitle="Page that Hosts a Frame"
  WindowWidth="250"
  WindowHeight="250">
<Frame Source="FramePage1.xaml" />
</Page>

此標記會將 Frame 元素的 Source 屬性設定為 Frame 應該一開始流覽的 Page 的 pack URI。This markup sets the Source attribute of the Frame element with a pack URI for the Page that the Frame should initially navigate to. 下圖顯示 XBAP,其中的 Page 具有在數個頁面之間流覽的 FrameThe following figure shows an XBAP with a Page that has a Frame that has navigated between several pages.

在多個頁面之間流覽的框架A frame that has navigated between multiple pages

您不只需要在 Page的內容內使用 FrameYou don't only have to use Frame inside the content of a Page. Window內容中裝載 Frame 也是很常見的情況。It is also common to host a Frame inside the content of a Window.

根據預設,只有在沒有另一個日誌時,Frame 才會使用自己的日誌。By default, Frame only uses its own journal in the absence of another journal. 如果 Frame 是裝載于 NavigationWindow 或 XBAP 內之內容的一部分,Frame 會使用屬於 NavigationWindow 或 XBAP 的日誌。If a Frame is part of content that is hosted inside either a NavigationWindow or an XBAP, Frame uses the journal that belongs to the NavigationWindow or XBAP. 不過,有時候 Frame 可能需要負責自己的日誌。Sometimes, though, a Frame might need to be responsible for its own journal. 若要這麼做,其中一個原因是允許在 Frame所裝載的頁面內進行日誌導覽。One reason to do so is to allow journal navigation within the pages that are hosted by a Frame. 如下圖所示。This is illustrated by the following figure.

框架和頁面圖表Frame and Page diagram

在此情況下,您可以將 FrameJournalOwnership 屬性設定為 OwnsJournal,以設定 Frame 使用自己的日誌。In this case, you can configure the Frame to use its own journal by setting the JournalOwnership property of the Frame to OwnsJournal. 下列標記顯示此做法。This is shown in the following markup.

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  WindowTitle="Page that Hosts a Frame"
  WindowWidth="250"
  WindowHeight="250">
<Frame Source="FramePage1.xaml" JournalOwnership="OwnsJournal" />
</Page>

下圖說明在使用自己的日誌的 Frame 中進行流覽的效果。The following figure illustrates the effect of navigating within a Frame that uses its own journal.

使用自己的日誌的框架A frame that uses its own journal

請注意,日誌項目會顯示在 Frame中的導覽 UIUI,而不是 Internet Explorer。Notice that the journal entries are shown by the navigation UIUI in the Frame, rather than by Internet Explorer.

注意

如果 Frame 是裝載于 Window中之內容的一部分,Frame 會使用自己的日誌,因此會顯示自己的流覽 UIUIIf a Frame is part of content that is hosted in a Window, Frame uses its own journal and, consequently, displays its own navigation UIUI.

如果您的使用者體驗需要 Frame 提供自己的日誌,而不顯示導覽 UIUI,您可以將 NavigationUIVisibility 設定為 [Hidden],以隱藏導覽 UIUIIf your user experience requires a Frame to provide its own journal without showing the navigation UIUI, you can hide the navigation UIUI by setting the NavigationUIVisibility to Hidden. 下列標記顯示此做法。This is shown in the following markup.

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  WindowTitle="Page that Hosts a Frame"
  WindowWidth="250"
  WindowHeight="250">
<Frame 
  Source="FramePage1.xaml" 
  JournalOwnership="OwnsJournal" 
  NavigationUIVisibility="Hidden" />
</Page>

FrameNavigationWindow 是稱為「導覽主機」的類別。Frame and NavigationWindow are classes that are known as navigation hosts. 導覽主機是可流覽並顯示內容的類別。A navigation host is a class that can navigate to and display content. 為了達成此目的,每個導覽主機都會使用自己的 NavigationService 和日誌。To accomplish this, each navigation host uses its own NavigationService and journal. 巡覽裝載的基本建構如下圖所示。The basic construction of a navigation host is shown in the following figure.

導覽器圖表Navigator diagrams

基本上,這可讓 NavigationWindowFrame 提供 XBAP 在瀏覽器中裝載時所提供的相同導覽支援。Essentially, this allows NavigationWindow and Frame to provide the same navigation support that an XBAP provides when hosted in the browser.

除了使用 NavigationService 和日誌以外,導覽主機還會實作為 NavigationService 所執行的相同成員。Besides using NavigationService and a journal, navigation hosts implement the same members that NavigationService implements. 如下圖所示。This is illustrated by the following figure.

畫面格和 NavigationWindow 中的日誌A journal in a Frame and in a NavigationWindow

這可讓您針對它們直接設計巡覽支援程式。This allows you to program navigation support directly against them. 如果您需要為裝載于 WindowFrame 提供自訂導覽 UIUI,您可以考慮這一點。You may consider this if you need to provide a custom navigation UIUI for a Frame that is hosted in a Window. 此外,這兩種類型都會執行其他的導覽相關成員,包括 BackStackNavigationWindow.BackStackFrame.BackStack)和 ForwardStackNavigationWindow.ForwardStackFrame.ForwardStack),這可讓您分別列舉後端堆疊和轉送堆疊中的記錄項目。Furthermore, both types implement additional, navigation-related members, including BackStack (NavigationWindow.BackStack, Frame.BackStack) and ForwardStack (NavigationWindow.ForwardStack, Frame.ForwardStack), which allow you to enumerate the journal entries in the back stack and forward stack, respectively.

如前所述,應用程式中可有多個日誌。As mentioned earlier, more than one journal can exist within an application. 下圖提供這種情況的範例。The following figure provides an example of when this can happen.

一個應用程式內的多個日誌Multiple journals within one application

在本主題中,Page 和 pack Xbap 都是用來示範 WPF 的各種導覽功能。Throughout this topic, Page and pack XBAPs have been used to demonstrate the various navigation capabilities of WPF. 不過,編譯成應用程式的 Page 不是可流覽的唯一內容類型,而套件 Xbap 則不是識別內容的唯一方法。However, a Page that is compiled into an application is not the only type of content that can be navigated to, and pack XBAPs aren't the only way to identify content.

如本節所示,您也可以流覽到鬆散的 XAMLXAML 檔案、HTML 檔案和物件。As this section demonstrates, you can also navigate to loose XAMLXAML files, HTML files, and objects.

鬆散的 XAMLXAML 檔案是具有下列特性的檔案:A loose XAMLXAML file is a file with the following characteristics:

  • 僅包含 XAMLXAML (也就是沒有程式碼)。Contains only XAMLXAML (that is, no code).

  • 具有適當的命名空間宣告。Has an appropriate namespace declaration.

  • 具有 .xaml 副檔名。Has the .xaml file name extension.

例如,請考慮將下列內容儲存為鬆散的 XAMLXAML 檔案、Person. xaml。For example, consider the following content that is stored as a loose XAMLXAML file, Person.xaml.

<!-- Person.xaml -->
<TextBlock xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <TextBlock FontWeight="Bold">Name:</TextBlock>
  <TextBlock>Nancy Davolio</TextBlock>
  <LineBreak />
  <TextBlock FontWeight="Bold">Favorite Color:</TextBlock>
  <TextBlock>Yellow</TextBlock>
</TextBlock>

當您按兩下檔案時,瀏覽器會開啟、巡覽至並顯示內容。When you double-click the file, the browser opens and navigates to and displays the content. 如下圖所示。This is shown in the following figure.

顯示 APP.XAML 檔案中的內容Display of the content in the Person.XAML file

您可以顯示來自下列的鬆散 XAMLXAML 檔案:You can display a loose XAMLXAML file from the following:

  • 在本機電腦、內部網路或網際網路上的網站。A Web site on the local machine, the intranet, or the Internet.

  • 通用命名慣例(UNC)檔案共用。A Universal Naming Convention (UNC) file share.

  • 本機磁碟。The local disk.

鬆散的 XAMLXAML 檔案可以新增至瀏覽器的 [我的最愛],或是瀏覽器的首頁。A loose XAMLXAML file can be added to the browser's favorites, or be the browser's home page.

注意

如需發佈和啟動鬆散 XAMLXAML 頁面的詳細資訊,請參閱部署 WPF 應用程式For more information about publishing and launching loose XAMLXAML pages, see Deploying a WPF Application.

鬆散 XAMLXAML 的一項限制是,您只能裝載可安全地在部分信任中執行的內容。One limitation with respect to loose XAMLXAML is that you can only host content that is safe to run in partial trust. 例如,Window 不能是鬆散 XAMLXAML 檔案的根項目。For example, Window cannot be the root element of a loose XAMLXAML file. 如需詳細資訊,請參閱 WPF 部分信任安全性For more information, see WPF Partial Trust Security.

如您所預期,您也可以流覽至 HTML。As you might expect, you can also navigate to HTML. 您只需要提供使用 HTTP 配置的 URI。You simply need to provide a URI that uses the http scheme. 例如,下列 XAMLXAML 顯示流覽至 HTML 網頁的 FrameFor example, the following XAMLXAML shows a Frame that navigates to an HTML page.

<Frame Source="http://www.microsoft.com/default.aspx" />

流覽至 HTML 需要特殊許可權。Navigating to HTML requires special permissions. 例如,您無法從在網際網路區域部分信任安全性沙箱中執行的 XBAP 進行流覽。For example, you can't navigate from an XBAP that is running in the Internet zone partial trust security sandbox. 如需詳細資訊,請參閱 WPF 部分信任安全性For more information, see WPF Partial Trust Security.

WebBrowser 控制項支援 HTML 檔案裝載、導覽和腳本/managed 程式碼互通性。The WebBrowser control supports HTML document hosting, navigation and script/managed code interoperability. 如需有關 WebBrowser 控制項的詳細資訊,請參閱 WebBrowserFor detailed information regarding the WebBrowser control, see WebBrowser.

如同 Frame,使用 WebBrowser 流覽至 HTML 需要特殊許可權。Like Frame, navigating to HTML using WebBrowser requires special permissions. 例如,您可以從部分信任的應用程式,只流覽至位於來源網站的 HTML。For example, from a partial-trust application, you can navigate only to HTML located at the site of origin. 如需詳細資訊,請參閱 WPF 部分信任安全性For more information, see WPF Partial Trust Security.

如果您有儲存為自訂物件的資料,顯示該資料的一種方式是使用系結至這些物件的內容來建立 Page (請參閱資料系結總覽)。If you have data that is stored as custom objects, one way to display that data is to create a Page with content that is bound to those objects (see Data Binding Overview). 如果您不需要建立整個頁面此額外負荷,而只要顯示物件,則您可以改為直接巡覽至它們。If you don't need the overhead of creating an entire page just to display the objects, you can navigate directly to them instead.

請考慮在下列程式碼中執行的 Person 類別。Consider the Person class that is implemented in the following code.

using System.Windows.Media;

namespace SDKSample
{
    public class Person
    {
        string name;
        Color favoriteColor;

        public Person() { }
        public Person(string name, Color favoriteColor)
        {
            this.name = name;
            this.favoriteColor = favoriteColor;
        }

        public string Name
        {
            get { return this.name; }
            set { this.name = value; }
        }

        public Color FavoriteColor
        {
            get { return this.favoriteColor; }
            set { this.favoriteColor = value; }
        }
    }
}

Namespace SDKSample
    Public Class Person
        Private _name As String
        Private _favoriteColor As Color

        Public Sub New()
        End Sub
        Public Sub New(ByVal name As String, ByVal favoriteColor As Color)
            Me._name = name
            Me._favoriteColor = favoriteColor
        End Sub

        Public Property Name() As String
            Get
                Return Me._name
            End Get
            Set(ByVal value As String)
                Me._name = value
            End Set
        End Property

        Public Property FavoriteColor() As Color
            Get
                Return Me._favoriteColor
            End Get
            Set(ByVal value As Color)
                Me._favoriteColor = value
            End Set
        End Property
    End Class
End Namespace

若要流覽至它,您可以呼叫 NavigationWindow.Navigate 方法,如下列程式碼所示。To navigate to it, you call the NavigationWindow.Navigate method, as demonstrated by the following code.

<Page 
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="SDKSample.HomePage"
  WindowTitle="Page that Navigates to an Object">
<Hyperlink Name="hyperlink" Click="hyperlink_Click">
  Navigate to Nancy Davolio
</Hyperlink>
</Page>
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace SDKSample
{
    public partial class HomePage : Page
    {
        public HomePage()
        {
            InitializeComponent();
        }

        void hyperlink_Click(object sender, RoutedEventArgs e)
        {
            Person person = new Person("Nancy Davolio", Colors.Yellow);
            this.NavigationService.Navigate(person);
        }
    }
}

Namespace SDKSample
    Partial Public Class HomePage
        Inherits Page
        Public Sub New()
            InitializeComponent()
        End Sub

        Private Sub hyperlink_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
            Dim person As New Person("Nancy Davolio", Colors.Yellow)
            Me.NavigationService.Navigate(person)
        End Sub
    End Class
End Namespace

其結果如下圖所示。The following figure shows the result.

流覽至類別的頁面A page that navigates to a class

在此圖中,您看不到任何有用的內容。From this figure, you can see that nothing useful is displayed. 事實上,顯示的值是Person物件之 ToString 方法的傳回值;根據預設,這是 WPF 可以用來代表物件的唯一值。In fact, the value that is displayed is the return value of the ToString method for the Person object; by default, this is the only value that WPF can use to represent your object. 您可以覆寫 ToString 方法以傳回更有意義的資訊,但它仍然只是字串值。You could override the ToString method to return more meaningful information, although it will still only be a string value. 您可以使用的一種技術,利用 WPF 的呈現功能,就是使用資料範本。One technique you can use that takes advantage of the presentation capabilities of WPF is to use a data template. 您可以執行 WPF 可以與特定類型的物件產生關聯的資料範本。You can implement a data template that WPF can associate with an object of a particular type. 下列程式碼顯示 Person 物件的資料範本。The following code shows a data template for the Person object.

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SDKSample" 
    x:Class="SDKSample.App"
    StartupUri="HomePage.xaml">

  <Application.Resources>

    <!-- Data Template for the Person Class -->
    <DataTemplate DataType="{x:Type local:Person}">
      <TextBlock xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
        <TextBlock FontWeight="Bold">Name:</TextBlock>
        <TextBlock Text="{Binding Path=Name}" />
        <LineBreak />
        <TextBlock FontWeight="Bold">Favorite Color:</TextBlock>
        <TextBlock Text="{Binding Path=FavoriteColor}" />
      </TextBlock>
    </DataTemplate>
    
  </Application.Resources>

</Application>

在這裡,資料範本會使用 DataType 屬性中的 x:Type 標記延伸,與 Person 類型相關聯。Here, the data template is associated with the Person type by using the x:Type markup extension in the DataType attribute. 然後,資料範本會將 TextBlock 元素(請參閱 TextBlock)系結至 Person 類別的屬性。The data template then binds TextBlock elements (see TextBlock) to the properties of the Person class. 下圖顯示 Person 物件的更新外觀。The following figure shows the updated appearance of the Person object.

流覽至具有資料範本的類別Navigating to a class that has a data template

這項技術的優點是可以取得一致性,因為能夠重複使用資料範本,所以應用程式任何位置都可顯示一致的物件。An advantage of this technique is the consistency you gain by being able to reuse the data template to display your objects consistently anywhere in your application.

如需資料範本的詳細資訊,請參閱資料範本化總覽For more information on data templates, see Data Templating Overview.

安全性Security

WPF 導覽支援可讓您透過網際網路流覽 Xbap,並允許應用程式裝載協力廠商內容。WPF navigation support allows XBAPs to be navigated to across the Internet, and it allows applications to host third-party content. 為了保護應用程式和使用者免于有害的行為,WPF 提供了安全性WPF 部分信任安全性中所討論的各種安全性功能。To protect both applications and users from harmful behavior, WPF provides a variety of security features that are discussed in Security and WPF Partial Trust Security.

請參閱See also