Wpf,silverlight and XAML Reading notes 15th-page between navigation page data transfer

Source: Internet
Author: User

? Description: This series is basically a reading note from the secrets of WPF. In the structure arrangement and the article content to refer to "The WPF Revelation" The arrangement, summarizes the content and joins some personal understanding.

Navigation

The topic of navigation is mentioned in the introduction of elements such as NavigationWindow and page. This article will analyze the navigation related topics in detail. With other topics, for Wpf,silverlight and WP 7, the navigation characteristics are roughly similar and somewhat different. The same attributes will be combined when describing this feature, and the unique features of each framework will be introduced independently and clearly identified.

The function and purpose of navigation is to move from one page to another, either forward or backward/back. Here are a few ways to implement navigation:

    • Calling the Navigate method
    • Using hyperlink
    • Using the Navigation Log

    1. Calling the Navigate method

The navigation container supports changing the content page of the Navigate method by using the. The Navigate method has two overloads that accept either the instance of the target page or the URI that points to the target page, respectively. Also, the two overloads have an equivalent implementation of the property setting, which is primarily used to set these two values declaratively in XAML, using the two overloads of navigate in code, and the C # code implementations of all these methods in the following code example:

Navigating through a Page instance
Photopage npage = new Photopage ();
This. Navigationservice.navigate (Npage);
Navigating to a page instance by property
This. Navigationservice.content = npage;
Navigating through a URI
This. Navigationservice.navigate (New Uri ("Photopage.xaml", urikind.relative));
Navigating to a URI by property
This. Navigationservice.source = new Uri ("Photopage.xaml", urikind.relative);

?

The page that the URI points to can be a generic XAML file, or it can be a compiled content. The required requirement is that the root element is page. If you want to navigate to an HTML page, you need to use navigate to receive the overloads of the URI, such as;

This. Navigationservice.navigate (New   Uri ("http://www.microsoft.com"));

    1. Using hyperlink

hyperlink in WPF is very similar to hyperlinks in HTML, providing an easy-to-use navigation scheme. The hyperlink element can be embedded in the TextBlock element and will automatically be rendered as a clickable hyperlink style (as in HTML <a> tags are automatically formatted). HYPERLINK specifies the target page of the navigation through the NavigateUri property (just like the href attribute of the <a> tag in HTML).

Tips:

HTML-like hyperlinks can use the target property to specify which frame the target page opens in, and hyperlink in WPF can also specify the target page to open in that frame by using the TargetName property, TargetName property is the name of the frame.

In addition to WPF, hyperlink also supports the effect of anchor points in HTML, similar to HTML, which is followed by a # after the URI, followed by the name of an element in the page, indicating the part to navigate to.

If you want to do some styling while navigating, you can assign a false path to the NavigateUri property and handle the Click event, complete the styling in this event, and call the Navigate method to complete the navigation manually.

    1. Using the Navigation Log

The navigation log is the navigation history information that is recorded by all navigation containers. Web browsers also have this feature. The navigation log provides back and forward functionality through two stacks – the forward stack and the back stack.

The two stacks work in the following ways:

Action

Results

Back off

Pushes the current page into the Forward stack, pops up a page from the back stack, and navigates to this page

Forward

Push the current page into the back stack, pop up a page from the forward stack, and navigate to the page

Go to New page

Pushes the current page into the back stack and empties the forward stack

To complete the forward and backward actions, you can invoke the GoBack and GoForward methods of the navigation container, noting that you need to call CanGoBack or CanGoForward before calling to either method to ensure that the back stack or forward stack is not empty. This ensures that the navigation behavior is performed correctly and without errors.

NavigationWindow always saves the navigation log, and if the frame saves the navigation log depends on the setting of its Journalownership property value, there are several settings:

    • Ownsjournal:frame has its own navigation log.
    • Usesparentjournal: The navigation log is saved in the parent container, and frame does not save the navigation log if the parent container does not support navigation logs.
    • Automatic (default): When frame is hosted on NavigationWindow or frame, use the same settings as usesparentjournal, otherwise use the same settings as ownsjournal.

In the case where frame has a navigation log, the built-in navigation button appears in the frame, and of course you can hide the navigation button by setting Navigationuivisibility to hidden.

Tips:

When navigating to a page through a URI (either by calling the Navigate method or through the hyperlink control), an instance of this page is created even if the pages have been accessed (of course, You can control whether a new instance of the page is created by calling navigate to accept the overloaded construction method of the page instance. This is if you need to maintain shared data between multiple instances of the same page, either by using a static variable or by using the Application.properties property.

In addition, when using navigation log navigation, set the Journalentry.keepalive attached property to true to force the page to reuse the same example.

Tip: How do I stop and refresh when I use the navigation log?

These two features do not have built-in button support, which can be accomplished by invoking the methods in the navigation container:

  • Stoploading method: You can stop a navigation operation that is being processed at any event.
  • Refresh method: The current Page object in the container can be refreshed. (This is equivalent to the URI instance that passed in the current page to the Navigate method, with the only difference being that the value passed to the navigating event handler contains a Navigationmode.refresh, so event handlers can be handled differently)

Both of these methods have no parameters.

Tips:

You can remove the page from the navigation log by setting the Removefromjournal property of the page to True. This property enables sequential access to each page (this property of the page that is being accessed is set to true to ensure that the user cannot perform a back operation).

Tip: You can use the navigation log for other actions

The navigation log allows users to add customizations that are easy to implement (thanks to the two stacks of navigation log maintenance), some such as application-level undo/redo capabilities rather than navigation.

The following details the process of implementing a custom undo action (undo image rotation) using the navigation log. First we need to create a class that derives from the CustomContentState abstract class, implement the replay method in the parent class, and override the Journalentryname property (which is optional). This replay method is called when a forward or backward operation occurs. The implementation of this subclass is as follows:

[Serializable]
Class Rotatestate:customcontentstate
{
FrameworkElement element;
Double rotation;

Public Rotatestate (FrameworkElement element, double rotation)
{
This.element = element;
This.rotation = rotation;
}

public override String Journalentryname
{
get { return "Rotate " + Rotation + ". ¡ê "; }
}

public override void Replay (NavigationService navigationservice, NavigationMode mode)
{
Element. LayoutTransform = new RotateTransform (rotation);
}
}

? then call NavigationService's AddBackEntry method where it needs to be undone, using an instance of the subclass above as a parameter. This allows you to add a custom record to the navigation log. Code such as:

void Fix_rotateclockwise_click (Object   sender, RoutedEventArgs e)
{
This. Navigationservice.addbackentry (Image, new rotatestate (image) . LayoutTransform as RotateTransform). Angle));
(Image. LayoutTransform as RotateTransform). Angle + = 90;
}

?

This will invoke the replay method of the Rotatestate object of this custom record in the navigation log when the undo operation occurs, to achieve the revocation of the operation.

In contrast to the built-in page navigation, the initial object rotation operation is equivalent to navigating to a new page. This time the customizations are added to the back stack of the navigation log, emptying the forward stack. When the undo operation occurs, the custom item pops up from the back stack, executes the replay method defined in it, and is then pressed into the forward stack. The process is reversed when the forward operation is called again.

Navigation events

The 3 navigation methods described above are performed asynchronously, and in this process, many events are triggered sequentially, and you can handle these events to complete such as displaying progress UI, and even to cancel navigation in event handling. The following two graphs show the sequence-triggered events during navigation:

When the page is loaded for the first time, all the triggered navigation events are as follows

Navigation events that are triggered when navigating between pages:

As the above flowchart shows, the navigationprocess is periodically called before the navigated event is triggered. In this process, if an error occurs or the navigation is canceled, the navigationstopped event (not the LoadCompleted event) is triggered.

Tips:

These navigation events (see), which have the same name as the navigation container, are defined in application to handle navigation events for all navigation containers (including child navigation containers) in a uniform place (application objects).

Note: Where the navigation event is triggered

When navigating between WPF pages or navigating between WPF pages and HTML pages, WPF navigation events are triggered, and when navigating between HTML pages, anger triggers these events and is not recorded in the navigation log.

Data transfer

Similar to HTML-based Web applications that use the way data is encoded into URLs for inter-page data passing, WPF's navigation process also requires data to be passed between pages, and the following describes how nightly data is delivered in WPF:

Passing data to a page

    • Method 1:

      WPF can pass parameters in the navigation process, which is supported by overloading the Navigate method. For the navigate overload that receives the page instance and the overload that receives the URI, there is one overload that receives another parameter as the data passed during navigation. Such as:

      int photoid = 10;
      Navigating to a page instance and passing parameters
      This. Navigationservice.navigate (New Photopage (), photoid);
      Navigating through URIs and passing parameters
      This. Navigationservice.navigate (New Uri ("Photopage.xaml", urikind.relative), photoid);

      ?

The loadcompleted event of the navigation container needs to be handled in the target page, and the data passed by the original page is obtained from the Extradata property of the event arguments (parameters of type NavigationEventArgs). The code is:


Loadcompletedeventhandler (container_loadcompleted);
...
void Container_loadcompleted (object sender, NavigationEventArgs e)
{
if (e.extradata! = null)
Loadphoto ((int) e.extradata);
}

?

    • Method 2:

      This method is simpler, adding a property to the target page of the navigation to store the data that you want to pass through during navigation, and provides a constructor that makes it easy to set this property. You then pass in an overload of the Navigate method that receives the page instance, passing in an instance of the target page initialized with the data to be passed. This enables the transfer of data. Code such as:

      Target page Constructors
      public photopage (int id)
      {
      Loadphoto (ID);
      or store the ID in the property
      }
      Navigating to a Page instance
      Photopage next = new Photopage (3);
      This. Navigationservice.navigate (next);

      ?

One obvious benefit of this way of passing is that the argument is strongly typed without having to make a null or type judgment.

    • Method 3:

      Using the Properties collection of the Application object to share global data, see the Introduction to application objects. If method 1, this method is not type-safe.

Returning data from a page via PageFunction

To meet this requirement (navigate to each page, do something, and then automatically return to the previous page, and pass the new data back, is one example):

WPF provides a class called PageFunction to complete the mechanism of returning data to the previous page in a type-safe manner, and automatically back to the previous page. Shows the new process.

PageFunction inherits from page, which is itself a page, and its primary function is to return data. Visual Studio provides a template for creating PageFunction:

The PageFunction form created through this template is as follows:

1 <PageFunction2 xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"3 xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"4 Xmlns:sys= "Clr-namespace:system;assembly=mscorlib"5 x:class= "Wpfapplication1.pagefunction1"6 x:typearguments= "Sys:string"7 XMLNS:MC= "http://schemas.openxmlformats.org/markup-compatibility/2006"8 xmlns:d= "http://schemas.microsoft.com/expression/blend/2008"9 mc:ignorable= "D"Ten D:designheight= "+"D:designwidth= "+" One Title= "PageFunction1"> A <Grid> - </Grid> - </PageFunction>

PageFunction is a generic class (pagefunction<t>) in which the type parameter represents the type of the returned data. This type parameter is defined in x:TypeArguments in the above XAML. Because the return value of PageFunction must be a string, the x:TypeArguments value in PageFunction needs to be sys:string. This class is also guaranteed to be type-safe with generic pagefunction.

The process of implementing this section through PageFunction is as follows:

Create an instance of PageFunction
PageFunction1 next = new pagefunction1<string> ();
Navigate to this pagefunction like navigating to the General page
This. Navigationservice.navigate (next);
return value for handling PageFunction return event in source page
(in PageFunction)
Next. Return + = new returneventhandler<string> (Nextpage_return);
void Next_return (Object sender, returneventargs<string> e)
{
String returnvalue = E.result;
}

?

As can be seen from the above code, the result property of the event handler parameter is consistent with the return type of PageFunction. Internally, the returned data is wrapped in the ReturnEventArgs object. When returned, PageFunction the OnReturn method in the base class, triggering the event and returning the data:

OnReturn (New   returneventargs<string> ("the Data"));

?

End of this article

Reference:

The Secrets of WPF

Wpf,silverlight and XAML Reading notes 15th-page between navigation page data transfer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.