In UWP, how does one uniformly process the page rollback logic between different devices?

Source: Internet
Author: User
Tags new set

In UWP, how does one uniformly process the page rollback logic between different devices?

I haven't written a blog to record my learning experience for a while. It seems a bit embarrassing to recall that some things have been done during this period. So far, it has been time for me to accept and enrich myself.

In this article, the author intends to tell UWP developers a realistic problem that is frequently encountered during development:Page rollback logic.

As we all know, UWP applications can theoretically run on a variety of devices on Windows, including Windows PC, Windows Mobile, XBox, and IOT. When our UWP application runs on different devices, we need to consider the page rollback logic between different devices, we need to consider how to design page rollback between different devices to better meet user needs. Therefore, it is necessary to encapsulate the page rollback logic between different devices in a unified manner. This will not only facilitate code maintenance, but also facilitate expansion of the rollback function, achieves "High Cohesion and low coupling". For convenience, I will only briefly discuss how to handle the page rollback logic of different platforms when our UWP application runs on PCs and Mobile. When an application runs on a PC, page rollback is usually performed by clicking a rollback button provided by the application. However, when our application runs on Mobile, users are more willing to use the physical rewind key provided on the mobile phone device for page rollback. As a result, we need to use the encapsulation idea for encapsulation.

1. Theoretical Analysis:

In the new MSDN, Microsoft provides us with a new set of Apis:SystemNavigationManager.When a UWP application runs on a PC, through this API, we can provide a rollback button for the application to indicate that the page can be rolled back, after you click this button, the page is successfully rolled back. However, when our UWP application is running on Mobile, if we still use this method to roll back the page, it may not be very friendly to users. Therefore, we want to recommend that you use the physical backend key on the mobile phone device to implement the corresponding page rollback logic. The corresponding API is:HardwareButtons. BackPressed. After analyzing this, we basically understand how to deal with the difference in the rollback logic between the two devices.So, the problem is coming.:Where should we put this logic? When is this logic suitable?There are two subjective questions: benevolent and wise. Here, I will discuss a method for beginners.

Because the application will trigger the App when it is started. the OnLaunched () function, so we need to modify the OnLaunched () function. Secondly, to ensure the uniqueness of the page, we use the "framework page" method to carry different pages, the page Jump is completed through Frame. Finally, we need to implement a theme framework of the application using a user control.

To sum up, let the application load our user control, let the user control carry our framework page, and let the framework page Jump to the application page.

Does it feel like a detour ?? It doesn't matter. Next let's take a look at how to write the actual code ..................

2. Code implementation:

First:

We need to create a page Jump Service class for our applications: NavigationService, which encapsulates the page rollback logic between different platforms. It should be pointed out that because this class uses different rollback logic, we can add extension references to which platform to use the rollback logic of which platform, I will only add extension references for Mobile here. The code is very simple. I believe you will take a look.

1 public class NavigationService 2 {3 public static NavigationService Instance {get; protected set;} 4 5 private Frame frame; 6 7 public Stack <Type> PageStack {get; protected set ;} 8 9 public NavigationService (ref Frame frame) 10 {11 if (Instance! = Null) 12 {13 throw new Exception ("Only one navigation service can exist in a App. "); 14} 15 Instance = this; 16 this. frame = frame; 17 this. pageStack = new Stack <Type> (); 18 19 SystemNavigationManager. getForCurrentView (). backRequested + = NavigationService_BackRequested; 20 if (ApiInformation. isTypePresent ("Windows. phone. UI. input. hardwareButtons ") 21 {22 HardwareButtons. backPressed + = HardwareButtons_Ba CkPressed; 23} 24} 25 26 public void NavigateTo (Type pageType, object parameter) 27 {28 if (PageStack. count> 0) 29 {30 // returns the object at the top of the Stack but does not remove it. 31 if (PageStack. peek () = pageType) 32 {33 return; 34} 35} 36 PageStack. push (pageType); 37 frame. navigate (pageType, parameter); 38 UpdateBackButtonVisibility (); 39} 40 41 public void NavigateToHome () 42 {43 while (frame. canGoBack) 44 {45 frame. goBack (); 46 UpdatePageStack (); 47} 48 UpdateBackButtonVisibility (); 49} 50 private void UpdatePageStack () 51 {52 if (PageStack. count> 0) 53 {54 PageStack. pop (); 55} 56} 57 58 private void UpdateBackButtonVisibility () 59 {60 SystemNavigationManager. GetForCurrentView (). AppViewBackButtonVisibility = frame. CanGoBack? 61 AppViewBackButtonVisibility. visible: AppViewBackButtonVisibility. collapsed; 62} 63 64 private void HardwareButtons_BackPressed (object sender, BackPressedEventArgs e) 65 {66 if (frame. canGoBack) 67 {68 frame. goBack (); 69 UpdatePageStack (); 70 e. handled = true; 71} 72} 73 74 private void NavigationService_BackRequested (object sender, BackRequestedEventArgs e) 75 {76 if (frame. canGoBack) 77 {78 frame. goBack (); 79 UpdatePageStack (); 80} 81 UpdateBackButtonVisibility (); 82} 83}View Code

 

Second:

The page Jump Service class is encapsulated. Next we need to create a user control to carry the main framework of the application.

1 <UserControl 2 x: Class = "NavigationDemo. ShellView" 3 xmlns =" http://schemas.microsoft.com/winfx/2006/xaml /Presentation "4 xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "5 xmlns: local =" using: NavigationDemo "6 xmlns: d =" http://schemas.microsoft.com/expression/blend/2008 "7 xmlns: mc =" http://schemas.openxmlformats.org/markup-compatibility/2006 "8 mc: Ignorable =" d "9 d: DesignHeight =" 300 "10 d: DesignWidth =" 400 "> 11 <UserControl. resources> 12 <x: String x: Key = "home"> homepage </x: String> 13 <x: String x: Key = "article"> article </x: string> 14 <x: String x: Key = "question"> problem </x: String> 15 <x: String x: Key = "thing"> things </x: string> 16 </UserControl. resources> 17 <Grid> 18 <SplitView IsPaneOpen = "True" DisplayMode = "CompactInline" OpenPaneLength = "100"> 19 <SplitView. pane> 20 <ListView> 21 <ListViewItem x: Name = "homeCmd" Content = "{StaticResource home}"> 22 <ListViewItem x: name = "articleCmd" Content = "{StaticResource article}"/> 23 <ListViewItem x: Name = "questionCmd" Content = "{StaticResource question}"/> 24 <ListViewItem x: name = "thingCmd" Content = "{StaticResource thing}"/> 25 </ListView> 26 </SplitView. pane> 27 <SplitView. content> 28 <Frame x: Name = "frame" x: FieldModifier = "public"/> 29 </SplitView. content> 30 </SplitView> 31 32 </Grid> 33 </UserControl>View Code

 

Then:

The main framework control has been designed. Next we will modify and modify the App class. We need to provide a global page jump for the application to facilitate use. Secondly, we need to transform the initial Page of the application into a user control, this ensures that the reference program always loads a user control.

1 public static NavigationService NavService {get; set;} 2 3 protected override void OnLaunched (LaunchActivatedEventArgs e) 4 {5 // ShellView is the user control we created 6 ShellView rootFrame = Window. current. content as ShellView; 7 8 // Do not repeat app initialization when the Window already has content, 9 // just ensure that the window is active10 if (rootFrame = null) 11 {12 // Create a Frame to act as the navigation context and navigate to the first page13 rootFrame = new ShellView (); 14 if (rootFrame. frame = null) // frame is the framework page 15 {16 rootFrame created in the user control. frame = new Frame (); 17} 18 NavService = new NavigationService (ref rootFrame. frame); 19 20 rootFrame. frame. navigationFailed + = OnNavigationFailed; 21 22 if (e. previusexecutionstate = ApplicationExecutionState. terminated) 23 {24 // TODO: Load state from previusly suspended application25} 26 27 // Place the frame in the current Window28 Window. current. content = rootFrame; 29} 30 31 if (rootFrame. frame. content = null) 32 {33 // When the navigation stack isn't restored navigate to the first page, 34 // loading the new page by passing required information as a navigation35 // parameter36 // ensure that the application initially loads the specified homepage 37 NavService. navigateTo (typeof (MainPage), e. arguments); 38} 39 // Ensure the current window is active40 Window. current. activate (); 41}View Code

 

Finally:

The Code has been almost completed here. Now everything is ready, and we have nothing to worry about. register our jump events. Here I just jump to four pages, and my friends with a big brain hole can design several more pages. Register the page jump event for the global menu of the application in the background code corresponding to our user control.

1 private void homeCmd_Tapped (object sender, TappedRoutedEventArgs e) 2 {3 App. navService. navigateToHome (); 4} 5 6 private void articleapps_tapped (object sender, TappedRoutedEventArgs e) 7 {8 App. navService. navigateTo (typeof (BlankPage1), null); 9} 10 11 private void questionCmd_Tapped (object sender, TappedRoutedEventArgs e) 12 {13 App. navService. navigateTo (typeof (BlankPage2), null); 14} 15 16 private void thingpai_tapped (object sender, TappedRoutedEventArgs e) 17 {18 App. navService. navigateTo (typeof (BlankPage3), null); 19}View Code

 

Well, this is a success. Let's take a look at the actual running effect.

This is the effect of running on the PC. The effect of running on the mobile phone is similar to this, but the page rollback is completed by using the physical back key. Interested friends can try it on their own.

It should be noted that if you run it on your mobile phone, you will find that this method will give you an additionalEgg: When we need to set the color of the system title bar, we can implement it in our user control, even if we need to fill in an image or other complex elements, it can be done through a few simple lines of XAML code.

3. Summary:

   I wonder if this method can meet your actual needs? With tens of millions of requests and continuous code changes, as a programmer, we must not only improve our coding capabilities, but also improve our problem-solving capabilities. Here is a brief summary of the knowledge used:

Encapsulation ideas;

User Control;

Framework page;

It seems that there is no such thing :)

 

 

So much nonsense, I wonder if you can understand it ??? As the saying goes: practice is a real thing. Therefore, it is recommended that you try it yourself.

Click to download an example

  

Related Article

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.