Visão Geral de Navegação Estruturada
Content that can be hosted by an XAML browser application (XBAP), a Frame, or a NavigationWindow is composed of pages that can be identified by pack uniform resource identifiers (URIs) and navigated to by hyperlinks. The structure of pages and the ways in which they can be navigated, as defined by hyperlinks, is known as a navigation topology. Such a topology suits a variety of application types, particularly those that navigate through documents. For such applications, the user can navigate from one page to another page without either page needing to know anything about the other.
However, other types of applications have pages that do need to know when they have been navigated between. For example, consider a human resources application that has one page to list all the employees in an organization—the "List Employees" page. This page could also allow users to add a new employee by clicking a hyperlink. When clicked, the page navigates to an "Add an Employee" page to gather the new employee's details and return them to the "List Employees" page to create the new employee and update the list. This style of navigation is similar to calling a method to perform some processing and return a value, which is known as structured programming. As such, this style of navigation is known as structured navigation.
The Page class doesn't implement support for structured navigation. Instead, the PageFunction<T> class derives from Page and extends it with the basic constructs required for structured navigation. This topic shows how to establish structured navigation using PageFunction<T>.
Este tópico contém as seguintes seções.
- Structured Navigation
- Structured Navigation with PageFunction
- Other Types of Structured Navigation
- Tópicos relacionados
Structured Navigation
When one page calls another page in a structured navigation, some or all of the following behaviors are required:
The calling page navigates to the called page, optionally passing parameters required by the called page.
The called page, when a user has completed using the calling page, returns specifically to the calling page, optionally:
Returning state information that describes how the calling page was completed (for example, whether a user pressed an OK button or a Cancel button).
Returning that data that was collected from the user (for example, new employee details).
When the calling page returns to the called page, the called page is removed from navigation history to isolate one instance of a called page from another.
These behaviors are illustrated by the following figure.
You can implement these behaviors by using a PageFunction<T> as the called page.
Structured Navigation with PageFunction
This topic shows how to implement the basic mechanics of structured navigation involving a single PageFunction<T>. In this sample, a Page calls a PageFunction<T> to get a String value from the user and return it.
Creating a Calling Page
The page that calls a PageFunction<T> can be either a Page or a PageFunction<T>. In this example, it is a Page, as shown in the following code.
<Page
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
x:Class="StructuredNavigationSample.CallingPage"
WindowTitle="Calling Page"
WindowWidth="250" WindowHeight="150">
...
</Page>
Imports System.Windows ' RoutedEventArgs, RoutedEventHandler, Visibility
Imports System.Windows.Controls ' Page
Imports System.Windows.Navigation ' ReturnEventArgs
Namespace StructuredNavigationSample
Public Class CallingPage
Inherits Page
Public Sub New()
Me.InitializeComponent()
...
End Sub
...
End Class
End Namespace
using System.Windows; // RoutedEventArgs, RoutedEventHandler, Visibility
using System.Windows.Controls; // Page
using System.Windows.Navigation; // ReturnEventArgs
namespace StructuredNavigationSample
{
public partial class CallingPage : Page
{
public CallingPage()
{
InitializeComponent();
...
}
...
}
}
Creating a Page Function to Call
Because the calling page can use the called page to collect and return data from the user, PageFunction<T> is implemented as a generic class whose type argument specifies the type of the value that the called page will return. The following code shows the initial implementation of the called page, using a PageFunction<T>, which returns a String.
<PageFunction
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
x:Class="StructuredNavigationSample.CalledPageFunction"
x:TypeArguments="sys:String"
Title="Page Function"
WindowWidth="250" WindowHeight="150">
<Grid Margin="10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition />
</Grid.RowDefinitions>
<!-- Data -->
<Label Grid.Column="0" Grid.Row="0">DataItem1:</Label>
<TextBox Grid.Column="1" Grid.Row="0" Name="dataItem1TextBox"></TextBox>
<!-- Accept/Cancel buttons -->
<TextBlock Grid.Column="1" Grid.Row="1" HorizontalAlignment="Right">
<Button Name="okButton" IsDefault="True" MinWidth="50">OK</Button>
<Button Name="cancelButton" IsCancel="True" MinWidth="50">Cancel</Button>
</TextBlock>
</Grid>
</PageFunction>
Imports System ' String
Imports System.Windows ' RoutedEventArgs, RoutedEventHandler
Imports System.Windows.Navigation ' PageFunction
Namespace StructuredNavigationSample
Public Class CalledPageFunction
Inherits PageFunction(Of String)
Public Sub New()
Me.InitializeComponent()
End Sub
...
End Class
End Namespace
using System; // String
using System.Windows; // RoutedEventArgs, RoutedEventHandler
using System.Windows.Navigation; // PageFunction
namespace StructuredNavigationSample
{
public partial class CalledPageFunction : PageFunction<String>
{
public CalledPageFunction()
{
InitializeComponent();
}
...
}
}
The declaration of a PageFunction<T> is similar to the declaration of a Page with the addition of the type arguments. As you can see from the code example, the type arguments are specified in both XAML markup, using the x:TypeArguments attribute, and code-behind, using standard generic type argument syntax.
You don't have to use only .NET Framework classes as type arguments. A PageFunction<T> could be called to gather domain-specific data that is abstracted as a custom type. The following code shows how to use a custom type as a type argument for a PageFunction<T>.
Public Class CustomType
...
End Class
namespace SDKSample
{
public class CustomType
{
...
}
}
<PageFunction
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.CustomTypePageFunction"
x:TypeArguments="local:CustomType">
...
</PageFunction>
Partial Public Class CustomTypePageFunction
Inherits System.Windows.Navigation.PageFunction(Of CustomType)
using System.Windows.Navigation; // PageFunction
namespace SDKSample
{
public partial class CustomTypePageFunction : PageFunction<CustomType>
{
The type arguments for the PageFunction<T> provide the foundation for the communication between a calling page and the called page, which are discussed in the following sections.
As you'll see, the type that is identified with the declaration of a PageFunction<T> plays an important role in returning data from a PageFunction<T> to the calling page.
Calling a PageFunction and Passing Parameters
To call a page, the calling page must instantiate the called page and navigate to it using the Navigate method. This allows the calling page to pass initial data to the called page, such as default values for the data being gathered by the called page.
O código a seguir mostra a página chamada com um construtor não-padrão para aceitar os parâmetros a partir da página de chamada.
Imports System ' String
Imports System.Windows ' RoutedEventArgs, RoutedEventHandler
Imports System.Windows.Navigation ' PageFunction
Namespace StructuredNavigationSample
Public Class CalledPageFunction
Inherits PageFunction(Of String)
...
Public Sub New(ByVal initialDataItem1Value As String)
Me.InitializeComponent()
...
' Set initial value
Me.dataItem1TextBox.Text = initialDataItem1Value
End Sub
...
End Class
End Namespace
using System; // String
using System.Windows; // RoutedEventArgs, RoutedEventHandler
using System.Windows.Navigation; // PageFunction
namespace StructuredNavigationSample
{
public partial class CalledPageFunction : PageFunction<String>
{
...
public CalledPageFunction(string initialDataItem1Value)
{
InitializeComponent();
...
// Set initial value
this.dataItem1TextBox.Text = initialDataItem1Value;
}
...
}
}
O código a seguir mostra o tratamento de página chamada a Click o evento da Hyperlink para instanciar a página de chamada e passe um valor de seqüência de caracteres inicial.
Imports System.Windows ' RoutedEventArgs, RoutedEventHandler, Visibility
Imports System.Windows.Controls ' Page
Imports System.Windows.Navigation ' ReturnEventArgs
Namespace StructuredNavigationSample
Public Class CallingPage
Inherits Page
Public Sub New()
Me.InitializeComponent()
AddHandler Me.pageFunctionHyperlink.Click, New RoutedEventHandler(AddressOf Me.pageFunctionHyperlink_Click)
End Sub
Private Sub pageFunctionHyperlink_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
...
End Sub
...
End Class
End Namespace
using System.Windows; // RoutedEventArgs, RoutedEventHandler, Visibility
using System.Windows.Controls; // Page
using System.Windows.Navigation; // ReturnEventArgs
namespace StructuredNavigationSample
{
public partial class CallingPage : Page
{
public CallingPage()
{
InitializeComponent();
this.pageFunctionHyperlink.Click += new RoutedEventHandler(pageFunctionHyperlink_Click);
}
void pageFunctionHyperlink_Click(object sender, RoutedEventArgs e)
{
// Instantiate and navigate to page function
CalledPageFunction CalledPageFunction = new CalledPageFunction("Initial Data Item Value");
...
}
...
}
}
<Hyperlink Name="pageFunctionHyperlink">Call Page Function</Hyperlink>
You are not required to pass parameters to the called page. Instead, you could do the following:
From the calling page:
Instantiate the called PageFunction<T> using the default constructor.
Store the parameters in Properties.
Navigate to the called PageFunction<T>.
From the called PageFunction<T>:
- Retrieve and use the parameters stored in Properties.
But, as you'll see shortly, you'll still need use code to instantiate and navigate to the called page to collect the data returned by the called page. For this reason, the PageFunction<T> needs to be kept alive; otherwise, the next time you navigate to the PageFunction<T>, WPF instantiates the PageFunction<T> using the default constructor.
Before the called page can return, however, it needs to return data that can be retrieved by the calling page.
Returning Task Result and Task Data from a Task to a Calling Page
Once the user has finished using the called page, signified in this example by pressing either the OK or Cancel buttons, the called page needs to return. Since the calling page used the called page to collect data from the user, the calling page requires two types of information:
Whether the user canceled the called page (by pressing either the OK button or the Cancel button in this example). This allows the calling page to determine whether to process the data that the calling page gathered from the user.
The data that was provided by the user.
To return information, PageFunction<T> implements the OnReturn method. The following code shows how to call it.
Imports System ' String
Imports System.Windows ' RoutedEventArgs, RoutedEventHandler
Imports System.Windows.Navigation ' PageFunction
Namespace StructuredNavigationSample
Public Class CalledPageFunction
Inherits PageFunction(Of String)
...
Private Sub okButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Accept when Ok button is clicked
Me.OnReturn(New ReturnEventArgs(Of String)(Me.dataItem1TextBox.Text))
End Sub
Private Sub cancelButton_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Cancel
Me.OnReturn(Nothing)
End Sub
End Class
End Namespace
using System; // String
using System.Windows; // RoutedEventArgs, RoutedEventHandler
using System.Windows.Navigation; // PageFunction
namespace StructuredNavigationSample
{
public partial class CalledPageFunction : PageFunction<String>
{
...
void okButton_Click(object sender, RoutedEventArgs e)
{
// Accept when Ok button is clicked
OnReturn(new ReturnEventArgs<string>(this.dataItem1TextBox.Text));
}
void cancelButton_Click(object sender, RoutedEventArgs e)
{
// Cancel
OnReturn(null);
}
}
}
In this example, if a user presses the Cancel button, a value of null is returned to the calling page. Se o botão OK for pressionado em vez disso, o valor de seqüência de caracteres fornecido pelo usuário é retornado. OnReturné um protected virtual método chamar para retornar os dados para a página de chamada. Your data needs to be packaged in an instance of the generic ReturnEventArgs<T> type, whose type argument specifies the type of value that Result returns. In this way, when you declare a PageFunction<T> with a particular type argument, you are stating that a PageFunction<T> will return an instance of the type that is specified by the type argument. In this example, the type argument and, consequently, the return value is of type String.
When OnReturn is called, the calling page needs some way of receiving the return value of the PageFunction<T>. For this reason, PageFunction<T> implements the Return event for calling pages to handle. When OnReturn is called, Return is raised, so the calling page can register with Return to receive the notification.
Imports System.Windows ' RoutedEventArgs, RoutedEventHandler, Visibility
Imports System.Windows.Controls ' Page
Imports System.Windows.Navigation ' ReturnEventArgs
Namespace StructuredNavigationSample
Public Class CallingPage
Inherits Page
...
Private Sub pageFunctionHyperlink_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
' Instantiate and navigate to page function
Dim calledPageFunction As New CalledPageFunction("Initial Data Item Value")
AddHandler calledPageFunction.Return, New ReturnEventHandler(Of String)(AddressOf Me.calledPageFunction_Return)
MyBase.NavigationService.Navigate(calledPageFunction)
End Sub
Private Sub calledPageFunction_Return(ByVal sender As Object, ByVal e As ReturnEventArgs(Of String))
Me.pageFunctionResultsTextBlock.Visibility = Windows.Visibility.Visible
' Display result
Me.pageFunctionResultsTextBlock.Text = IIf((Not e Is Nothing), "Accepted", "Canceled")
' If page function returned, display result and data
If (Not e Is Nothing) Then
Me.pageFunctionResultsTextBlock.Text = (Me.pageFunctionResultsTextBlock.Text & ChrW(10) & e.Result)
End If
End Sub
End Class
End Namespace
using System.Windows; // RoutedEventArgs, RoutedEventHandler, Visibility
using System.Windows.Controls; // Page
using System.Windows.Navigation; // ReturnEventArgs
namespace StructuredNavigationSample
{
public partial class CallingPage : Page
{
...
void pageFunctionHyperlink_Click(object sender, RoutedEventArgs e)
{
// Instantiate and navigate to page function
CalledPageFunction CalledPageFunction = new CalledPageFunction("Initial Data Item Value");
CalledPageFunction.Return += pageFunction_Return;
this.NavigationService.Navigate(CalledPageFunction);
}
void pageFunction_Return(object sender, ReturnEventArgs<string> e)
{
this.pageFunctionResultsTextBlock.Visibility = Visibility.Visible;
// Display result
this.pageFunctionResultsTextBlock.Text = (e != null ? "Accepted" : "Canceled");
// If page function returned, display result and data
if (e != null)
{
this.pageFunctionResultsTextBlock.Text += "\n" + e.Result;
}
}
}
}
Removing Task Pages When a Task Completes
When a called page returns, and the user didn't cancel the called page, the calling page will process the data that was provided by the user and also returned from the called page. Data acquisition in this way is usually an isolated activity; when the called page returns, the calling page needs to create and navigate to a new calling page to capture more data.
However, unless a called page is removed from the journal, a user will be able to navigate back to a previous instance of the calling page. Whether a PageFunction<T> is retained in the journal is determined by the RemoveFromJournal property. By default, a page function is automatically removed when OnReturn is called because RemoveFromJournal is set to true. To keep a page function in navigation history after OnReturn is called, set RemoveFromJournal to false.
Other Types of Structured Navigation
This topic illustrates the most basic use of a PageFunction<T> to support call/return structured navigation. This foundation provides you with the ability to create more complex types of structured navigation.
For example, sometimes multiple pages are required by a calling page to gather enough data from a user or to perform a task. The use of multiple pages is referred to as a "wizard".
In other cases, applications may have complex navigation topologies that depend on structured navigation to operate effectively. For more information, see Visão geral sobre topologias de navegação.