Compartilhar via


Visão geral de navegação

Windows Presentation Foundation (WPF)oferece suporte a navegação no estilo de navegador que pode ser usada em dois tipos de aplicativos: aplicativos autônomos e XAML browser applications (XBAPs). O conteúdo do pacote para navegação, WPF fornece a Page classe. Você pode navegar de um Page para outro declarativamente, usando um Hyperlink, ou programaticamente, usando o NavigationService. WPF usa o diário se lembrar de páginas que navegou de e para navegar de volta para eles.

Page, Hyperlink, NavigationService, and the journal form the core of the navigation support offered by WPF. Esta visão geral explora desses recursos detalhadamente antes de abordar o suporte de navegação avançada inclui navegação perder Extensible Application Markup Language (XAML) arquivos, HTML , os arquivos e objetos.

Observação

Neste tópico, o termo "navegador" refere-se somente a navegadores que podem hospedar WPF aplicativos, que atualmente inclui Microsoft Internet Explorer e Firefox.Onde específico WPF recursos são suportados apenas por um determinado navegador, a versão do navegador é chamada.

Este tópico contém as seguintes seções.

  • Navigation in WPF Applications
  • The NavigationWindow Class
  • The Frame Class
  • Navigation Hosts
  • Navegar para um conteúdo diferente de páginas XAML
  • Security
  • Tópicos relacionados

This topic provides an overview of the key navigation capabilities in WPF. These capabilities are available to both standalone applications and XBAPs, although this topic presents them within the context of an XBAP.

Observação

This topic doesn't discuss how to build and deploy XBAPs.For more information on XBAPs, see Visão geral sobre WPF XAML Browser Applications.

This section explains and demonstrates the following aspects of navigation:

  • Implementing a Page

  • Configuring a Start Page

  • Configuring the Host Window's Title, Width, and Height

  • Hyperlink Navigation

  • Fragment Navigation

  • Navigation Service

  • Programmatic Navigation with the Navigation Service

  • Navigation Lifetime

  • Remembering Navigation with the Journal

  • Page Lifetime and the Journal

  • Retaining Content State with Navigation History

  • Cookies

  • Structured Navigation

Implementing a Page

In WPF, you can navigate to several content types that include .NET Framework objects, custom objects, enumeration values, user controls, XAML files, and HTML files. However, you'll find that the most common and convenient way to package content is by using Page. Furthermore, Page implements navigation-specific features to enhance their appearance and simplify development.

Using Page, you can declaratively implement a navigable page of XAML content by using markup like the following.

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

A Page that is implemented in XAML markup has Page as its root element and requires the WPF XML namespace declaration. The Page element contains the content that you want to navigate to and display. You add content by setting the Page.Content property element, as shown in the following markup.

<Page xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <Page.Content>
    <!-- Page Content -->
    Hello, Page!
  </Page.Content>
</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 Sistema de layout) to contain and compose your 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="https://schemas.microsoft.com/winfx/2006/xaml/presentation">
  <!-- Page Content -->
  Hello, Page!
</Page>

In this case, Page.Content is automatically set with the child elements of the Page element. For more information, see Modelo de conteúdo WPF.

A markup-only Page is useful for displaying content. 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. An interactive Page is implemented by using a combination of markup and code-behind, as shown in the following example.

<Page
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.HomePage">
  Hello, from the XBAP HomePage!
</Page>

Imports System.Windows.Controls ' Page

Namespace SDKSample
    Partial Public Class HomePage
        Inherits Page
        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace
using System.Windows.Controls; // Page

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

To allow a markup file and code-behind file to work together, the following configuration is required:

  • In markup, the Page element must include the x:Class attribute. Quando o aplicativo é criado, a existência de x:Class na marcação do arquivo faz com que Microsoft build engine (MSBuild) para criar um partial classe que deriva de Page e tem o nome especificado pelo x:Class atributo. This requires the addition of an XML namespace declaration for the XAML schema (xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"). Gerado partial classe implementa InitializeComponent, que é chamado para registrar os eventos e definir as propriedades que são implementados na marcação.

  • In 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. 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 (WPF)).

  • No code-behind, o Page classe deve implementar um construtor que chama o InitializeComponent método. InitializeComponenté implementada pela marcação da gerado o arquivo partial classe para registrar eventos e definir propriedades que são definidas na marcação.

Observação

When you add a new Page to your project using Microsoft 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.

Once you have a Page, you can navigate to it. To specify the first Page that an application navigates to, you need to configure the start Page.

Configuring a Start Page

XBAPs require a certain amount of application infrastructure to be hosted in a browser. In WPF, the Application class is part of an application definition that establishes the required application infrastructure (see Visão Geral do Gerenciamento de Aplicativo).

Uma definição de aplicativo geralmente é implementada usando marcação e o code-behind, com o arquivo de marcação, configurado como um MSBuild ApplicationDefinition item. A seguir está uma definição de aplicativo para um XBAP.

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

Imports System.Windows ' Application

Namespace SDKSample
    Partial Public Class App
        Inherits Application
    End Class
End Namespace
using System.Windows; // Application

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

Um XBAP pode usar a sua definição de aplicativo para especificar um início Page, que é o Page que é carregado automaticamente quando o XBAP é iniciado. Fazer isso, definindo a StartupUri propriedade com o uniform resource identifier (URI) para o desejado Page.

Observação

In most cases, the Page is either compiled into or deployed with an application.Nesses casos, o URI que identifica um Page é um pacote de URI, que é um URI que está em conformidade com o pack esquema.Pacote de URIs são discutidas mais na Pack URIs in WPF. Você também pode navegar para o conteúdo usando o esquema de http, o que é discutido abaixo.

You can set StartupUri declaratively in markup, as shown in the following example.

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

Neste exemplo, o StartupUri atributo está definido com um pacote relativo URI que identifica o /homepage.XAML. Quando o XBAP é iniciado, /homepage.XAML é navegada e exibidos automaticamente. This is demonstrated by the following figure, which shows an XBAP that was launched from a Web server.

Página XBAP

Observação

For more information regarding the development and deployment of XBAPs, see Visão geral sobre WPF XAML Browser Applications and Implantar um aplicativo WPF (WPF).

Configuring the Host Window's Title, Width, and Height

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. For this reason, Page offers a way for you to change the title by setting the WindowTitle property. Furthermore, you can configure the width and height of the browser window by setting WindowWidth and WindowHeight, respectively.

WindowTitle, WindowWidth, and WindowHeight can be set declaratively in markup, as shown in the following example.

<Page
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://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.

Título, altura e largura da janela

Uma típica XBAP abrange várias páginas. A maneira mais simples de navegar de uma página para outra é usar um Hyperlink. Declarativamente, você pode adicionar um Hyperlink para um Page usando o Hyperlink elemento, que é mostrado a marcação a seguir.

<Page
  xmlns="https://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>

A Hyperlink element requires the following:

  • The pack URI of the Page to navigate to, as specified by the NavigateUri attribute.

  • 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).

A figura a seguir mostra um XBAP com um Page que tem um Hyperlink.

Página com hiperlink

Como você esperava, clicando no Hyperlink faz com que o XBAP para navegar até o Page que é identificado pelo NavigateUri atributo. Além disso, o XBAP adiciona uma entrada para o anterior Page à lista de páginas recentes na Internet Explorer. This is shown in the following figure.

Botões Voltar e Avançar

As well as supporting navigation from one Page to another, Hyperlink also supports fragment navigation.

Fragment Navigation

Fragment navigation is the navigation to a content fragment in either the current Page or another Page. In WPF, a content fragment is the content that is contained by a named element. A named element is an element that has its Name attribute set. The following markup shows a named TextBlock element that contains a content fragment.

<Page
    xmlns="https://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>

For a Hyperlink to navigate to a content fragment, the NavigateUri attribute must include the following:

  • The URI of the Page with the content fragment to navigate to.

  • A "#" character.

  • The name of the element on the Page that contains the content fragment.

Um fragmento de URI tem o formato a seguir.

PageURI#ElementName

The following shows an example of a Hyperlink that is configured to navigate to a content fragment.

<Page
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  WindowTitle="Page That Navigates To Fragment" >


...


<Hyperlink NavigateUri="PageWithFragments.xaml#Fragment1">
  Navigate To pack Fragment
</Hyperlink>


...


</Page>

Observação

Esta seção descreve a implementação padrão de navegação de fragmento no WPF.WPFtambém permite que você implementar seu próprio esquema de navegação de fragmento que, em parte, requer tratamento a NavigationService.FragmentNavigation de evento.

Observação importanteImportante

Você pode navegar para fragmentos em loose XAML páginas (apenas de marcação XAML arquivos com Page como o elemento raiz) somente se as páginas podem ser visitadas por meio de HTTP.

However, a loose XAML page can navigate to its own fragments.

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. Essentially, NavigationService provides the ability to process a navigation request on behalf of client code, such as the Hyperlink. Additionally, NavigationService implements higher-level support for tracking and influencing a navigation request.

Quando um Hyperlink for clicado, WPF chamadas NavigationService.Navigate para localizar e baixar o Page em que o pacote especificado URI. O download de Page é convertido em uma árvore de objetos cujo objeto raiz é uma instância do download Page. A reference to the root Page object is stored in the NavigationService.Content property. O pacote URI para o conteúdo que foi navegado até é armazenado na NavigationService.Source propriedade, enquanto o NavigationService.CurrentSource armazena o pacote URI para a última página foi navegada.

Observação

É possível que um WPF aplicativo tenha mais de um ativo no momento NavigationService.Para obter mais informações, consulte Os Hosts de navegação posteriormente neste tópico.

Programmatic Navigation with the Navigation Service

You don't need to know about NavigationService if navigation is implemented declaratively in markup using Hyperlink, because Hyperlink uses the NavigationService on your behalf. Isso significa que, desde que o pai direto ou indireto de um Hyperlink é um host de navegação (consulte Os Hosts de navegação), Hyperlink será capaz de localizar e usar o serviço de navegação do host de navegação para processar uma solicitação de navegação.

However, there are situations when you need to use NavigationService directly, including the following:

  • When you need to instantiate a Page using a non-default constructor.

  • When you need to set properties on the Page before you navigate to it.

  • When the Page that needs to be navigated to can only be determined at run time.

In these situations, you need to write code to programmatically initiate navigation by calling the Navigate method of the NavigationService object. That requires getting a reference to a NavigationService.

Getting a Reference to the NavigationService

Por motivos são abordados os Os Hosts de navegação seção, uma WPF aplicativo pode ter mais de um NavigationService. Isso significa que seu código precisa de uma maneira de localizar um NavigationService, que geralmente é o NavigationService que navegou atual Page. Você pode obter uma referência a um NavigationService chamando o static NavigationService.GetNavigationService método. To get the NavigationService that navigated to a particular Page, you pass a reference to the Page as the argument of the GetNavigationService method. O código a seguir mostra como obter o NavigationService para a atual Page.

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


...


// Get a reference to the NavigationService that navigated to this Page
NavigationService ns = NavigationService.GetNavigationService(this);

As a shortcut for finding the NavigationService for a Page, Page implements the NavigationService property. This is shown in the following example.

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


...


// Get a reference to the NavigationService that navigated to this Page
NavigationService ns = this.NavigationService;

Observação

A Page can only get a reference to its NavigationService when Page raises the Loaded event.

Programmatic Navigation to a Page Object

The following example shows how to use the NavigationService to programmatically navigate to a Page. Programmatic navigation is required because the Page that is being navigated to can only be instantiated using a single, non-default constructor. The Page with the non-default constructor is shown in the following markup and code.

<Page
    x:Class="SDKSample.PageWithNonDefaultConstructor"
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    Title="PageWithNonDefaultConstructor">

  <!-- Content goes here -->

</Page>

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
using System.Windows.Controls; // Page

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

            this.Content = message;
        }
    }
}

The Page that navigates to the Page with the non-default constructor is shown in the following markup and code.

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

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

</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
using System.Windows; // RoutedEventArgs
using System.Windows.Controls; // Page
using System.Windows.Navigation; // NavigationService

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);
        }
    }
}

Quando o Hyperlink sobre isso Page é clicado, navegação é iniciada pela instanciação a Page para navegar para o construtor não-padrão e a chamada a NavigationService.Navigate método. Navigateaceita uma referência ao objeto que o NavigationService navegarão para, em vez de um pacote de URI.

Programmatic Navigation with a Pack URI

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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.NSUriNavigationPage">
  <Hyperlink Click="hyperlink_Click">Navigate to Page by Pack URI</Hyperlink>
</Page>

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
using System; // Uri, UriKind
using System.Windows; // RoutedEventArgs
using System.Windows.Controls; // Page
using System.Windows.Navigation; // NavigationService

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);
        }
    }
}

Refreshing the Current Page

A Page is not downloaded if it has the same pack URI as the pack URI that is stored in the NavigationService.Source property. Para forçar a WPF para fazer download da página atual novamente, você pode chamar o NavigationService.Refresh método, conforme mostrado no exemplo a seguir.

<Page
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.NSRefreshNavigationPage">
 <Hyperlink Click="hyperlink_Click">Refresh this page</Hyperlink>
</Page>

Namespace SDKSample
    Partial Public Class NSRefreshNavigationPage
        Inherits Page


...


        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
using System.Windows; // RoutedEventArgs
using System.Windows.Controls; // Page
using System.Windows.Navigation; // NavigationService

namespace SDKSample
{
    public partial class NSRefreshNavigationPage : Page
    {


...


        void hyperlink_Click(object sender, RoutedEventArgs e)
        {
            // Force WPF to download this page again
            this.NavigationService.Refresh();
        }
    }
}

There are many ways to initiate navigation, as you've seen. 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:

  • Navigating. Ocorre quando uma nova navegação é solicitada. Can be used to cancel the navigation.

  • NavigationProgress. Ocorre periodicamente durante um download para fornecer informações de progresso de navegação.

  • Navigated. Ocorre quando a página foi localizada e baixada.

  • NavigationStopped. Ocorre quando a navegação é interrompida (chamando StopLoading), ou quando uma nova navegação é solicitada enquanto uma navegação atual está em andamento.

  • NavigationFailed. Ocorre quando um erro é gerado durante a navegação até o conteúdo solicitado.

  • LoadCompleted. Ocorre quando o conteúdo que foi navegado até é carregado e analisado e começou a renderização.

  • FragmentNavigation. Ocorre quando a navegação até um fragmento de conteúdo começa, o que acontece:

    • 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.

Fluxograma de navegação da página

In general, a Page isn't concerned about these events. It is more likely that an application is concerned with them and, for that reason, these events are also raised by the Application class:

Sempre que NavigationService gera um evento de Application classe gera o evento correspondente. Framee NavigationWindow oferecem os mesmos eventos para detectar a navegação dentro de seus respectivos escopos.

In some cases, a Page might be interested in these events. 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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.CancelNavigationPage">
  <Button Click="button_Click">Navigate to Another Page</Button>
</Page>

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
using System; // Uri, UriKind
using System.Windows; // RoutedEventArgs, MessageBox, MessageBoxResult
using System.Windows.Controls; // Page
using System.Windows.Navigation; // NavigationService, NavigatingCancelEventArgs

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;
        }
    }
}

If you register a handler with a navigation event from a Page, as the preceding example does, you must also unregister the event handler. 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

WPFusa duas pilhas lembrar as páginas que você navegou de: uma pilha traseira e uma pilha de encaminhamento. Quando você navega atual Page para um novo Page ou encaminhar a um existente Page, atual Page é adicionado para o pilha de volta. Quando você navega atual Page com o anterior Page, atual Page é adicionado para o pilha Avançar. A pilha de back, a pilha de encaminhamento e a funcionalidade para gerenciá-los, são coletivamente denominados diário. 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.

Conceitualmente, o diário funciona da mesma maneira que o novamente e frente botões na Internet Explorer pendente Eles são mostrados na figura a seguir.

Botões Voltar e Avançar

Para XBAPs que são hospedados por Internet Explorer, WPF integra o diário para a navegação UI de Internet Explorer. Isso permite aos usuários navegar as páginas em um XBAP usando o novamente, frente, e Páginas recentes botões na Internet Explorer. O diário não é integrado ao Microsoft Internet Explorer 6 da mesma maneira que é para Internet Explorer 7 ou o Internet Explorer 8. Instead, WPF renders a substitute navigation UI.

Observação importanteImportante

Em Internet Explorer, quando um usuário navega longe e volta para um XBAP, apenas as entradas de diário para páginas que não foram mantidas vivas são mantidas no diário.Para a discussão sobre como manter as páginas alive, consulte tempo de vida da página e o diário posteriormente neste tópico.

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. The attached JournalEntry.Name attribute value.

  2. The Page.Title attribute value.

  3. The Page.WindowTitle attribute value and the URI for the current Page.

  4. O URI para a atual Page. (Padrão)

The order in which the options are listed matches the order of precedence for finding the text. For example, if JournalEntry.Name is set, the other values are ignored.

The following example uses the Page.Title attribute to change the text that appears for a journal entry.

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


...


</Page>

Namespace SDKSample
    Partial Public Class PageWithTitle
        Inherits Page


...


    End Class
End Namespace
using System.Windows.Controls; // Page

namespace SDKSample
{
    public partial class PageWithTitle : Page
    {


...


    }
}

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. One reason to do this is to provide custom navigation UIs in your pages.

You can declaratively add journal navigation support by using the navigation commands exposed by NavigationCommands. The following example demonstrates how to use the BrowseBack navigation command.

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


...


<Hyperlink Command="NavigationCommands.BrowseBack">Back</Hyperlink>


...


<Hyperlink Command="NavigationCommands.BrowseForward">Forward</Hyperlink>


...


</Page>

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

Considere um XBAP com várias páginas que contêm conteúdo rico, incluindo elementos gráficos, animações e mídia. O rastro de memória para as páginas como essas pode ser muito grande, especialmente se a mídia de áudio e vídeo é usadas. Considerando que o diário "lembra" páginas que foram navigated para, como um XBAP pode consumir rapidamente uma quantidade grande e perceptível da memória.

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. When a journal entry is navigated to, its Page metadata is used to create a new instance of the specified Page. As a consequence, each Page that is navigated has the lifetime that is illustrated by the following figure.

Tempo de vida da página

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. If you need to retain a Page instance in the journal, you can draw on two techniques for doing so. First, you can programmatically navigate to a Page object by calling the NavigationService.Navigate method.

Em segundo lugar, você pode especificar que WPF reter uma instância de um Page no diário, definindo a KeepAlive propriedade para true (o padrão é false). Conforme mostrado no exemplo a seguir, você pode definir KeepAlive declarativamente na marcação.

<Page
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.KeepAlivePage"
    KeepAlive="True">

  An instance of this page is stored in the journal.

</Page>

The lifetime of a Page that is kept alive is subtly different from one that is not. The first time a Page that is kept alive is navigated to, it is instantiated just like a Page that is not kept alive. 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. 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. As shown in the following figure, the Loaded and Unloaded events are still raised each time a Page is navigated to and from, respectively.

Quando os eventos Loaded e Unloaded são gerados

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.

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.

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

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. 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.

Fortunately, the journal provides support for remembering data across Page navigations, including control data. Specifically, the journal entry for each Page acts as a temporary container for the associated Page state. The following steps outline how this support is used when a Page is navigated from:

  1. An entry for the current Page is added to the journal.

  2. The state of the Page is stored with the journal entry for that page, which is added to the back stack.

  3. The new Page is navigated to.

When the page Page is navigated back to, using the journal, the following steps take place:

  1. The Page (the top journal entry on the back stack) is instantiated.

  2. The Page is refreshed with the state that was stored with the journal entry for the Page.

  3. The Page is navigated back to.

WPFusa automaticamente esse suporte quando os seguintes controles são usados em um Page:

If a Page uses these controls, data entered into them is remembered across Page navigations, as demonstrated by the Favorite Color ListBox in the following figure.

Página com controles que lembram o estado

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.

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.

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.

Se você precisa navegar por vários estados de um único Page, sem precisar navegar a partir do Page propriamente dito, você pode usar IProvideCustomContentState e NavigationService.AddBackEntry.

Cookies

Outra maneira que WPF aplicativos podem armazenar dados é com cookies, que são criados, atualizados e excluídos usando o SetCookie e GetCookie métodos. Os cookies que você pode criar no WPF são os mesmos cookies que usam a outros tipos de aplicativos da Web; os cookies são partes arbitrárias de dados são armazenados por um aplicativo em uma máquina cliente, durante ou entre sessões do aplicativo. Cookie data typically takes the form of a name/value pair in the following format.

Nome=valor

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. This type of cookie is referred to as a session cookie.

To store a cookie across application sessions, an expiration date must be added to the cookie, using the following format.

NOME=valor; expires=DAY, DD-MMM-YYYY HH:MM:SS GMT

A cookie with an expiration date is stored in the current Windows installation's Temporary Internet Files folder until the cookie expires. Como um cookie é conhecido como um cookie persistente porque ele persista entre sessões do aplicativo.

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.

The following are some of the ways that cookies are supported in WPF:

  • WPFaplicativos autônomos e XBAPs pode criar e gerenciar cookies.

  • Cookies são criados por um XBAP pode ser acessado a partir do navegador.

  • XBAPsdo mesmo domínio pode criar e compartilhar os cookies.

  • XBAPse HTML páginas do mesmo domínio podem criar e compartilhar os cookies.

  • Cookies são expedidos quando XBAPs e solto XAML páginas fazer solicitações da Web.

  • Nível superior ambos XBAPs e XBAPs hospedados em IFRAMES podem acessar cookies.

  • Suporte de cookie no WPF é o mesmo para todos os navegadores com suporte.

  • Em Internet Explorer, a diretiva P3P, que diz respeito a cookies é respeitada por WPF, particularmente com respeito aos primários e de terceiros XBAPs.

Structured Navigation

If you need to pass data from one Page to another, you can pass the data as arguments to a non-default constructor of the Page. Observe que se você usar essa técnica, você deve manter a Page alive; Se não, na próxima vez que você navegue para o Page, WPF reinstantiates a Page usando o construtor padrão.

Alternatively, your Page can implement properties that are set with the data that needs to be passed. Things become tricky, however, when a Page needs to pass data back to the Page that navigated to it. 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. Para resolver esse problema, WPF fornece a PageFunction<T> classe que você pode usar para garantir que uma Page é retornado para em uma forma previsível e estruturado. Para obter mais informações, consulte Visão Geral de Navegação Estruturada.

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. These services were discussed in the context of XBAPs, although they are not limited to XBAPs. Os sistemas operacionais modernos e Windows aplicativos tirar proveito da experiência do navegador dos usuários modernos para incorporar a navegação no estilo de navegador em aplicativos autônomos. Exemplos comuns incluem:

  • Dicionário de sinônimos do Word: Navegue opções do word.

  • Arquivo Explorer: Navegar por arquivos e pastas.

  • Assistentes: Dividindo uma tarefa complexa em várias páginas que podem ser navegados entre. Um exemplo é o Assistente de componentes do Windows manipula adicionando e removendo Windows recursos.

Para incorporar a navegação no estilo de navegador para seus aplicativos autônomos, você pode usar o NavigationWindow classe. NavigationWindowderiva de Window e a estende com o mesmo suporte de navegação que XBAPs fornecer. Você pode usar NavigationWindow como a janela principal do aplicativo autônomo ou como uma janela secundária, como uma caixa de diálogo.

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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="SDKSample.MainWindow" 
    Source="HomePage.xaml"/>

Namespace SDKSample
    Partial Public Class MainWindow
        Inherits NavigationWindow
        Public Sub New()
            InitializeComponent()
        End Sub
    End Class
End Namespace
using System.Windows.Navigation; // NavigationWindow

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

This code creates a NavigationWindow that automatically navigates to a Page (HomePage.xaml) when the NavigationWindow is opened. 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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    StartupUri="MainWindow.xaml" />

The following figure shows the NavigationWindow as the main window of a standalone application.

Uma janela principal

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. Instead, the title is set using the WindowTitle property, which is shown in the following code.

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


...


</Page>

Setting the WindowWidth and WindowHeight properties also affects the NavigationWindow.

Usually, 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. Se você especificar o pacote URI de um Page como o StartupUri em um aplicativo autônomo, Application cria automaticamente um NavigationWindow para o host a Page. The following markup shows how to enable this.

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

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
            Dim dlg As New NavigationWindowDialogBox()
            dlg.Source = New Uri("HomePage.xaml", UriKind.Relative)
            dlg.Owner = Me
            dlg.ShowDialog()
// 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();

The following figure shows the result.

Uma caixa de diálogo

Como você pode ver, NavigationWindow exibe Internet Explorer-estilo novamente e frente os botões que permitem aos usuários navegar o diário. These buttons provide the same user experience, as shown in the following figure.

Botões Voltar e Avançar em uma 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.

Alternatively, you can use customization support in WPF to replace the UI of the NavigationWindow itself.

The Frame Class

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. Você pode inserir o conteúdo navegável em outros tipos de conteúdo usando o Frame classe. Framefornece o mesmo suporte para NavigationWindow e XBAPs.

The following example shows how to add a Frame to a Page declaratively by using the Frame element.

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


...


<Frame Source="FramePage1.xaml" />


...


</Page>

Essa marcação define o Source atributo da Frame elemento com um pacote de URI para o Page que o Frame inicialmente devem navegar. A figura a seguir mostra um XBAP com um Page que tem um Frame que navegou entre várias páginas.

Um quadro que navegou entre várias páginas

You don't only have to use Frame inside the content of a Page. It is also common to host a Frame inside the content of a Window.

By default, Frame only uses its own journal in the absence of another journal. Se um Frame faz parte do conteúdo que está hospedado em um um NavigationWindow ou um XBAP, Frame usa o diário ao qual pertence o NavigationWindow ou XBAP. Às vezes, porém, um Frame talvez precise ser responsável por seu próprio diário. 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.

Diagrama de quadros e páginas

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="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  WindowTitle="Page that Hosts a Frame"
  WindowWidth="250"
  WindowHeight="250">


...


<Frame Source="FramePage1.xaml" JournalOwnership="OwnsJournal" />


...


</Page>

The following figure illustrates the effect of navigating within a Frame that uses its own journal.

Um quadro que usa seu próprio diário

Observe que as entradas de diário são mostradas pela navegação UI na Frame, em vez de por Internet Explorer.

Observação

If a Frame is part of content that is hosted in a Window, Frame uses its own journal and, consequently, displays its own navigation UI.

If your user experience requires a Frame to provide its own journal without showing the navigation UI, you can hide the navigation UI by setting the NavigationUIVisibility to Hidden. This is shown in the following markup.

<Page 
  xmlns="https://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>

Frame and NavigationWindow are classes that are known as navigation hosts. A navigation host is a class that can navigate to and display content. 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.

Diagramas do navegador

Essentially, this allows NavigationWindow and Frame to provide the same navigation support that an XBAP provides when hosted in the browser.

Besides using NavigationService and a journal, navigation hosts implement the same members that NavigationService implements. This is illustrated by the following figure.

Um diário em Frame e em NavigationWindow

This allows you to program navigation support directly against them. Você pode considerar isso caso você precise fornecer uma navegação personalizada UI para um Frame que está hospedado em um Window. Além disso, ambos os tipos de implementam os membros adicionais, relacionados a navegação, incluindo BackStack (NavigationWindow.BackStack, Frame.BackStack) e ForwardStack (NavigationWindow.ForwardStack, Frame.ForwardStack), que permitem que você enumere as entradas de diário na pilha voltar e pilha Avançar, respectivamente.

As mentioned earlier, more than one journal can exist within an application. The following figure provides an example of when this can happen.

Vários diários dentro de um aplicativo

Em todo este tópico, Page e pacote de XBAPs foram usados para demonstrar as diversas capacidades de navegação do WPF. No entanto, um Page ou seja compilado em um aplicativo não é o único tipo de conteúdo que pode ser navegado e pack XBAPs não são a única maneira de identificar o conteúdo.

Como esta seção demonstra, você também pode navegar para loose XAML arquivos, HTML , os arquivos e objetos.

Um loose XAML é um arquivo com as seguintes características:

  • Contains only XAML (that is, no code).

  • Has an appropriate namespace declaration.

  • Has the .xaml file name extension.

For example, consider the following content that is stored as a loose XAML file, Person.xaml.

<!-- Person.xaml -->
<TextBlock xmlns="https://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.

Exibição do conteúdo no arquivo Person.XAML

You can display a loose XAML file from the following:

  • A Web site on the local machine, the intranet, or the Internet.

  • A Universal Naming Convention (UNC) file share.

  • The local disk.

A loose XAML file can be added to the browser's favorites, or be the browser's home page.

Observação

For more information about publishing and launching loose XAML pages, see Implantar um aplicativo WPF (WPF).

One limitation with respect to loose XAML is that you can only host content that is safe to run in partial trust. For example, Window cannot be the root element of a loose XAML file. For more information, see WPF Partial Trust Security.

As you might expect, you can also navigate to HTML. Você só precisa fornecer um URI que usa o esquema de http. Por exemplo, o seguinte XAML mostra um Frame que navega para um HTML página.

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

Navigating to HTML requires special permissions. Por exemplo, você não pode navegar de um XBAP que está executando na caixa de proteção de segurança de confiança parcial de zona Internet. Para obter mais informações, consulte WPF Partial Trust Security.

O WebBrowser controle suporta HTML documento hospedagem, navegação e o script/gerenciado interoperabilidade de código. Para obter informações detalhadas sobre o WebBrowser controle, consulte WebBrowser.

Como Frame, navegando para HTML usando WebBrowser requer permissões especiais. Por exemplo, de um aplicativo parcialmente confiável, você pode navegar somente a HTML localizado no site de origem. For more information, see WPF Partial Trust Security.

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 Revisão de Associação de Dados). If you don't need the overhead of creating an entire page just to display the objects, you can navigate directly to them instead.

Consider the Person class that is implemented in the following code.


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
using System.Windows.Media; // Color

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; }
        }
    }
}

To navigate to it, you call the NavigationWindow.Navigate method, as demonstrated by the following code.

<Page 
  xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="https://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>

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
using System.Windows; // RoutedEventArgs
using System.Windows.Controls; // Page
using System.Windows.Media; // Colors

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);
        }
    }
}

The following figure shows the result.

Página que navega até uma classe

From this figure, you can see that nothing useful is displayed. 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. You could override the ToString method to return more meaningful information, although it will still only be a string value. One technique you can use that takes advantage of the presentation capabilities of WPF is to use a data template. You can implement a data template that WPF can associate with an object of a particular type. The following code shows a data template for the Person object.

<Application
    xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="https://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="https://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>

Here, the data template is associated with the Person type by using the x:Type markup extension in the DataType attribute. The data template then binds TextBlock elements (see TextBlock) to the properties of the Person class. The following figure shows the updated appearance of the Person object.

Navegando até uma classe que tem um modelo de dados

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 Visão geral sobre Templating de dados.

Security

WPFo suporte de navegação permite que XBAPs ser navegada pela Internet e ele permite que os aplicativos host de conteúdo a terceiros. Para proteger os usuários e aplicativos do comportamento prejudicial, WPF fornece uma variedade de recursos de segurança que são discutidas em Segurança (WPF) e WPF Partial Trust Security.

Consulte também

Referência

SetCookie

GetCookie

Conceitos

Visão Geral do Gerenciamento de Aplicativo

Pack URIs in WPF

Visão Geral de Navegação Estruturada

Visão geral sobre topologias de navegação

Implantar um aplicativo WPF (WPF)

Outros recursos

Navigation How-to Topics