Windows 10 開發 - 快速指南



Windows 10 開發 - 簡介

本教程專為希望學習如何開發 Windows 10 應用程式的人員設計。在本教程中,我們將學習 -

  • Windows 10 應用程式開發
  • Microsoft 釋出的新作業系統的更新
  • 更新中為開發人員提供的新功能

現在有很多有趣的應用程式場景成為可能,這些場景在第一個版本中我們無法使用。Microsoft 不僅添加了新的 API,還擴充套件了現有的 API。

通用 Windows 應用

通用 Windows 應用最初在 Windows 8 中作為 Windows 執行時引入,它建立在通用應用程式平臺之上。

現在,在 Windows 10 中,通用應用程式平臺的名稱已更改為通用 Windows 平臺 (UWP)。您可以透過針對 Windows 應用商店的 Windows 10 裝置(如 PC、平板電腦、手機等)構建現代且完全沉浸式的應用。

Universal Windows app

在 Windows 10 中,您可以輕鬆開發應用程式以觸達 Windows 10 支援的所有裝置,只需 -

  • 一組 API
  • 一個應用包
  • 以及一個應用商店

通用 Windows 平臺還支援不同的螢幕尺寸和不同的互動模式,例如觸控板、滑鼠和鍵盤、遊戲控制器或筆。

UWP 應用的特點

以下是通用 Windows 應用的一些特性,使其優於 Windows 10。

  • 您可以針對裝置系列,而不是像 Windows 8.1 那樣針對作業系統。

  • 應用程式使用.AppX打包格式進行打包和分發,確保您的應用程式可以無縫部署和更新。

  • 您可以將應用程式提交到 Windows 應用商店,它將使應用程式在所有裝置系列或您選擇的裝置上可用。您可以在一個地方輕鬆管理所有 Windows 裝置的應用程式。

  • 您可以將應用程式的可用性限制在特定的裝置系列。

  • 通用 Windows 平臺 (UWP) 的核心 API 在所有 Windows 裝置系列中都是相同的。因此,如果您的應用僅使用核心 API,則它可以在所有 Windows 10 裝置上執行。

  • 藉助擴充套件 SDK,您可以為特定裝置啟用您的應用程式。

開發選擇

通用 Windows 應用程式可以使用以下任何語言建立 -

  • 使用 XAML 的 C# 或 Visual Basic
  • 使用 HTML 的 JavaScript
  • 使用 DirectX 和/或 XAML 的 C++

您還可以用一種語言編寫元件,並在用另一種語言開發的應用程式中使用它們。

Windows 10 開發 - UWP

Windows 執行時 (WinRT) 是一種平臺同構的應用程式架構,支援使用 C++/CX、C#、VB.NET 和 JavaScript 進行開發。WinRT 應用程式原生支援 x86 和 ARM 架構。一些重要特性是。

  • 它於 2012 年 9 月在 Windows Server 2012 中首次推出。

  • WinRT API 使用 JavaScript、C#、Visual Basic 和 C++ 提供對所有核心平臺功能的訪問。

  • WinRT 元件支援多種語言和 API,例如本機語言、託管語言和指令碼語言。

通用 Windows 平臺 (UWP)

通用 Windows 應用構建於通用 Windows 平臺 (UWP) 之上,該平臺最初在 Windows 8 中作為 Windows 執行時引入。在 Windows 10 中,引入了通用 Windows 平臺 (UWP),它進一步發展了 Windows 執行時 (WinRT) 模型。

  • 在 Windows 8.1 中,WinRT 首次在 Windows Phone 8.1 應用程式和 Windows 8.1 應用程式之間保持一致,藉助通用 Windows 8 應用來針對 Windows 手機和 Windows 應用程式使用共享程式碼庫。

  • Windows 10 統一核心(現在稱為 Windows Core)已發展到 UWP 現在提供可在每個執行 Windows 10 的裝置上使用的通用應用程式平臺的程度。

Universal Windows Platform
  • UWP 不僅可以呼叫所有裝置通用的 WinRT API,還可以呼叫特定於應用程式執行的裝置系列的 API(包括 Win32 和 .NET API)。

Windows 10 支援的裝置

Windows 8.1 和 Windows Phone 8.1 應用針對作業系統;Windows 或 Windows Phone。Windows 10 應用程式不針對作業系統,而是針對一個或多個裝置系列。

裝置系列也有自己的 API,這些 API 為特定裝置系列新增功能。您可以輕鬆確定 Windows 應用商店中應用程式可以安裝和執行的所有裝置系列中的所有裝置。以下是裝置系列的分層表示。

Windows Devices

UWP 的優勢

通用 Windows 平臺 (UWP) 為開發人員提供了大量功能。它們是 -

  • 所有裝置的一個作業系統和一個統一核心。
  • 一個應用程式平臺,可在每個系列中執行應用程式。
  • 一個開發中心提交應用程式和儀表板。
  • 所有裝置的一個應用商店。

UWP 開發設定

要開始為 Windows 10 建立自己的通用 Windows 平臺 (UWP) 應用,需要執行以下步驟。

  • Windows 10 作業系統 - UWP 應用需要最新版本的 Windows 才能開發。您也可以在 Windows 8.1 上開發 UWP 應用程式,但 UI 設計器視窗不受支援。

  • Windows 10 開發人員工具 - 在 Visual Studio 2015 中,您可以設計、編寫程式碼、測試和除錯 UWP 應用。您可以從 https://dev.windows.com/en-us/downloads下載並安裝免費的 Microsoft Visual Studio Community 2015。

  • 為 Windows 10 啟用開發模式 -

    • 轉到開始 > 設定

    • 選擇更新和安全

    • 然後選擇“開發者選項”

    • 點選開發者模式

對於 UWP 應用,在裝置上測試應用非常重要。

Developer Mode
  • 註冊為應用開發者 - 您可以開始開發應用,但要將應用提交到應用商店,您需要一個開發者帳戶。您可以在此處建立您的開發者帳戶https://msdn.microsoft.com/enus/library/windows/apps/bg124287.aspx

完成以上步驟後,您現在就可以開始開發通用 Windows 平臺 (UWP) 應用程式了。

Windows 10 開發 - 第一個應用

在本節中,我們將使用 XAML 和 C# 在 Windows 10 上的通用 Windows 平臺 (UWP) 中建立我們的第一個簡單應用程式“Hello world”。我們將演示如何在 Visual Studio 中建立的單個 UWP 應用程式如何在任何 Windows 10 裝置上執行和執行。

讓我們按照以下步驟開始建立應用。

  • 啟動 Visual Studio 2015。

  • 點選檔案選單,然後選擇新建 > 專案

First App
  • 將顯示以下新建專案對話方塊視窗。您可以在對話方塊左側窗格中看到不同型別的模板。

Blank App
  • 在左側窗格中,您可以看到樹形檢視。從模板 > Visual C# > Windows中選擇通用模板

  • 從中心窗格中,選擇空白應用(通用 Windows)模板

  • 透過在名稱欄位中輸入UWPHelloWorld來為專案命名。

  • 點選確定以建立一個新的 UWP 專案。

UWP Project
  • 您可以在解決方案資源管理器中看到新建立的專案。

  • 這是一個空白應用,但它包含許多檔案,這是任何 UWP 應用程式的最低要求。

  • MainPage.xamlMainPage.xaml.cs在您執行應用程式時執行。

  • 預設情況下,MainPage.xaml檔案包含以下資訊。

<Page 
   x:Class = ”UWPHellowWorld.MainPage” 
   xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation” 
   xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml” 
   xmlns:local = ”using:UWPHellowWorld” 
   xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008” 
   xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006” 
   mc:Ignorable = ”d”>  
	
   <Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”>
   </Grid>
	
</Page>
  • 以下是MainPage.xaml.cs中提供的預設資訊。

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 

using Windows.Foundation; 
using Windows.Foundation.Collections; 

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace UWPHellowWorld {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
      public MainPage(){ 
         this.InitializeComponent(); 
      } 
   } 
	
}
  • 讓我們新增一些文字塊、文字框和按鈕,如下面的 XAML 程式碼所示。

<Page 
   x:Class = ”UWPHellowWorld.MainPage” 
   xmlns = ”http://schemas.microsoft.com/winfx/2006/xaml/presentation” 
   xmlns:x = ”http://schemas.microsoft.com/winfx/2006/xaml” 
   xmlns:local = ”using:UWPHellowWorld” 
   xmlns:d = ”http://schemas.microsoft.com/expression/blend/2008”
   xmlns:mc = ”http://schemas.openxmlformats.org/markup-compatibility/2006” 
   mc:Ignorable = ”d”>  
   
   <Grid Background = ”{ThemeResource ApplicationPageBackgroundThemeBrush}”> 
	
      <StackPanel HorizontalAlignment = ”Center”> 
         <TextBlock Text = ”Hello, world!”  Margin = ”20”  Width = ”200” 
            HorizontalAlignment = ”Left”/> 
				
         <TextBlock Text = ”Write your name.” Margin = ”20” Width = ”200” 
            HorizontalAlignment = ”Left”/> 
				
         <TextBox x:Name = ”txtbox”  Width = ”280” Margin = ”20” 
            HorizontalAlignment = ”Left”/> 
				
         <Button x:Name = ”button” Content = ”Click Me” Margin = ”20” 
            Click = ”button_Click”/> 
				
         <TextBlock x:Name = ”txtblock” HorizontalAlignment = ”Left” 
            Margin = ”20”/> 
      </StackPanel> 
		
   </Grid> 
	
</Page> 
  • 以下是 C# 中的點選事件按鈕。
using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 

using System.Runtime.InteropServices.WindowsRuntime; 
using Windows.Foundation; 
using Windows.Foundation.Collections;
 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation; 
 
// The Blank Page item template is documented at
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace UWPHellowWorld {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
      public MainPage() {
         this.InitializeComponent(); 
      }  
		
      private void button_Click(object sender, RoutedEventArgs e) {
         if (txtbox.Text != “”) 
            txtblock.Text = “Hello: “ + txtbox.Text; 
         else 
            txtblock.Text = “You have not write your name”; 
      } 
		
   }	
	
}
  • 在 UWP 專案中,裝置預覽選項在設計視窗中可用,藉助該選項,您可以輕鬆更改佈局,以適合您針對應用程式的所有裝置系列中的所有裝置的螢幕尺寸。

Device Preview
  • 您可以在本地計算機、模擬器或模擬器或遠端裝置上執行和測試您的應用。您可以從以下選單中選擇目標裝置,如下所示 -

UWP Local Machine
  • 讓我們在本地計算機上執行上述程式碼,您將看到以下視窗。現在,在文字框中輸入任何名稱,然後點選點選我按鈕。

Local Machine
  • 現在,如果您想在模擬器上測試您的應用,您可以從選單中選擇一個特定的模擬器並執行您的應用程式。您將看到以下模擬器 -

Emulator

我們建議您使用不同的裝置執行上述應用程式。

Windows 10 開發 - 應用商店

Windows 應用商店對開發人員的好處在於您可以出售您的應用程式。您可以為每個裝置系列提交您的單個應用程式。

  • Windows 10 應用商店是提交應用程式的地方,以便使用者可以找到您的應用程式。

  • 在 Windows 8 中,應用商店僅限於應用程式,並且 Microsoft 提供許多應用商店,即 Xbox 音樂商店、Xbox 遊戲商店等。

Windows 8
  • 在 Windows 8 中,所有這些都是不同的應用商店,但在 Windows 10 中,它稱為 Windows 應用商店。它的設計方式是使用者可以在一個地方為所有 Windows 10 裝置找到各種應用、遊戲、歌曲、電影、軟體和服務。

Windows Store

貨幣化

貨幣化意味著在臺式機、移動裝置、平板電腦和其他裝置上銷售您的應用。有各種方法可以在 Windows 應用商店中銷售您的應用程式和服務以賺取一些錢。

您可以選擇以下任何方法 -

  • 最簡單的方法是在應用商店中提交您的應用,並提供付費下載選項。

  • 試用版選項,使用者可以在購買具有有限功能的應用之前試用您的應用。

  • 使用 Microsoft 廣告在您的應用中新增廣告。

Microsoft 廣告

當您在應用程式中新增廣告並且使用者點選該特定廣告時,廣告客戶將向您支付費用。Microsoft 廣告允許開發人員接收來自 Microsoft 廣告網路的廣告。

  • 用於通用 Windows 應用的 Microsoft 廣告 SDK 包含在 Visual Studio 2015 安裝的庫中。

  • 您也可以從visualstudiogallery安裝它。

  • 現在,您可以輕鬆地將影片和橫幅廣告整合到您的應用中。

讓我們看看 XAML 中的一個簡單示例,以使用AdControl在您的應用程式中新增橫幅廣告。

  • 建立一個名為UWPBannerAd的新通用 Windows 空白應用專案。

  • 解決方案資源管理器中,右鍵點選引用

UWP Banner Add
  • 選擇新增引用,這將開啟引用管理器對話方塊。

  • 從左側窗格中,在“通用 Windows”選項下選擇**擴充套件**,並選中**Microsoft Advertising SDK for XAML**。

Reference Manager
  • 單擊**確定**繼續。

  • 下面是添加了某些屬性的**AdControl**的 XAML 程式碼。

<Page 
   x:Class = "UWPBannerAd.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPBannerAd" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:UI = "using:Microsoft.Advertising.WinRT.UI" 
   mc:Ignorable = "d">
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <StackPanel HorizontalAlignment = "Center">
         <UI:AdControl ApplicationId = "d25517cb-12d4-4699-8bdc-52040c712cab"  
            AdUnitId = "10043121" HorizontalAlignment = "Left" Height = "580"  
            VerticalAlignment = "Top" Width = "800"/> 
      </StackPanel> 
   </Grid> 
	
</Page>

當以上程式碼在本地計算機上編譯並執行時,您將看到以下視窗,其中包含 MSN 橫幅。單擊此橫幅時,它將開啟 MSN 網站。

MSN Banner

您也可以在應用程式中新增**影片橫幅**。讓我們考慮另一個示例,其中當單擊**顯示廣告**按鈕時,它將播放 Xbox One 的影片廣告。

下面是 XAML 程式碼,其中我們演示瞭如何新增具有某些屬性和事件的按鈕。

<Page 
   x:Class = "UWPBannerAd.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPBannerAd" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   xmlns:UI = "using:Microsoft.Advertising.WinRT.UI" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <StackPanel HorizontalAlignment = "Center"> 
         <Button x:Name = "showAd" Content = "Show Ad" HorizontalAlignment = "Left"  
            Margin = "138,296,0,0" VerticalAlignment = "Top" FontSize = "48" 
            Click = "showAd_Click"/> 
      </StackPanel> 
   </Grid> 
	
</Page>

下面是在 C# 中的單擊事件實現。

using Microsoft.Advertising.WinRT.UI; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;
  
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace UWPBannerAd {

   /// <summary>
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
      InterstitialAd videoAd = new InterstitialAd();
		
      public MainPage() {
         this.InitializeComponent(); 
      }  
		
      private void showAd_Click(object sender, RoutedEventArgs e) {
         var MyAppId = "d25517cb-12d4-4699-8bdc-52040c712cab"; 
         var MyAdUnitId = "11388823";  
         videoAd.AdReady += videoAd_AdReady; 
         videoAd.RequestAd(AdType.Video, MyAppId, MyAdUnitId); 
      }
		
      void videoAd_AdReady(object sender, object e){ 
         if ((InterstitialAdState.Ready) == (videoAd.State)) {
            videoAd.Show(); 
         } 
      } 
		
   } 
	
}

當以上程式碼在本地計算機上編譯並執行時,您將看到以下視窗,其中包含**顯示廣告**按鈕。

Show Add

現在,當您單擊**顯示廣告**按鈕時,它將在您的應用程式中播放影片。

Show Add Button

Windows 10 開發 - XAML 控制元件

XAML 代表可擴充套件應用程式標記語言。它是一個使用者介面框架,它提供了一個廣泛的控制元件庫,支援 Windows 的 UI 開發。其中一些具有視覺表示形式,例如按鈕、文字框和文字塊等;而其他控制元件則用作其他控制元件或內容(例如影像等)的容器。所有 XAML 控制元件都繼承自**“System.Windows.Controls.Control”**。

XAML 新興故事

XAML 用於許多重要的 Microsoft 平臺,例如 Windows Presentation Foundation (WPF)、Silverlight 和現在的 Windows 應用。現在,Microsoft Office 2016 也是 UWP 應用系列的一部分。XAML 是一個豐富的平臺,它提供了非常酷的功能和控制元件,可用於 UWP 應用程式。

控制元件的完整繼承層次結構如下所示。

Inheritance Hierarchy

佈局控制元件

控制元件的佈局對於應用程式可用性非常重要且至關重要。它用於在應用程式中排列一組 GUI 元素。在選擇佈局面板時,需要考慮某些重要事項 -

  • 子元素的位置。
  • 子元素的大小。
  • 子元素相互疊加的分層。

下面列出了**佈局控制元件** -

序號 控制元件和說明
1

StackPanel

**StackPanel** 是 XAML 中一個簡單而有用的佈局面板。在 StackPanel 中,子元素可以基於方向屬性沿水平或垂直方向排列成單行。

2

WrapPanel

在**WrapPanel** 中,子元素按順序從左到右或從上到下排列,具體取決於方向屬性。StackPanel 和 WrapPanel 之間的唯一區別在於它不會將所有子元素堆疊到單行中,而是如果剩餘空間不足,則將剩餘元素換行。

3

DockPanel

**DockPanel** 定義了一個區域,用於相對於彼此(水平或垂直)排列子元素。使用 DockPanel,您可以輕鬆地使用 Dock 屬性將子元素停靠到頂部、底部、右側、左側和中心。

使用**LastChildFill** 屬性,當為該元素設定時,最後一個子元素將填充剩餘空間,而不管任何其他停靠值如何。

4

Canvas

**Canvas** 是基本佈局面板,其中子元素可以使用相對於任何邊(例如左側、右側、頂部和底部)的座標顯式定位。Canvas 通常用於 2D 圖形元素(例如 Ellipse、Rectangle 等),但不適用於 UI 元素,因為在 XAML 應用程式中指定絕對座標會在調整大小、本地化或縮放時造成麻煩。

5

Grid

**Grid** 提供了一個靈活的區域,該區域由行和列組成。在 Grid 中,子元素可以以表格形式排列。可以透過使用**Grid.Row** 和**Grid.Column** 屬性將元素新增到任何特定的行和列。

6

SplitView

**SplitView** 表示一個包含兩個檢視的容器;一個檢視用於主要內容,另一個檢視通常用於導航命令。

7

RelativePanel

**RelativePanel** 定義一個區域,您可以在其中相對於彼此或父面板定位和對齊子物件。

8

ViewBox

**ViewBox** 定義一個內容裝飾器,可以拉伸和縮放單個子元素以填充可用空間。

9

FlipView

**FlipView** 表示一個專案控制元件,一次顯示一個專案,並啟用“翻轉”行為以遍歷其專案集合。

10

GridView

**GridView** 是一種控制元件,以行和列的形式呈現專案集合,並且可以水平滾動。

UI 控制元件

以下是 UI 控制元件的列表,這些控制元件對終端使用者可見。

序號 UI 控制元件和說明
1

Button

響應使用者輸入的控制元件

2

Calendar

表示一個控制元件,使使用者能夠透過使用可視日曆顯示來選擇日期。

3

CheckBox

使用者可以選擇或清除的控制元件。

4

ComboBox

專案的下拉列表,使用者可以從中選擇。

5

ContextMenu

獲取或設定應在每次透過使用者介面 (UI) 從此元素內部請求上下文選單時出現的上下文選單元素。

6

DataGrid

表示一個控制元件,以可自定義的網格顯示資料。

7

DatePicker

允許使用者選擇日期的控制元件。

8

Dialogs

應用程式還可以顯示其他視窗,以便使用者收集或顯示重要資訊。

9

Flyout

表示一個控制元件,顯示輕量級 UI,這些 UI 要麼是資訊,要麼需要使用者互動。與對話方塊不同,Flyout 可以透過單擊或點選其外部、按裝置的返回按鈕或按“Esc”鍵輕鬆關閉。

10

Image

顯示影像的控制元件。

11

ListBox

顯示使用者可以從中選擇的專案內聯列表的控制元件。

12

Menus

表示一個 Windows 選單控制元件,使您能夠分層組織與命令和事件處理程式關聯的元素。

13

MenuFlyout

表示顯示命令選單的彈出選單。

14

PasswordBox

用於輸入密碼的控制元件。

15

Popup

在應用程式視窗的範圍內,在現有內容的頂部顯示內容。

16

ProgressBar

透過顯示條形來指示進度的控制元件。

17

ProgressRing

透過顯示環形來指示不確定進度的控制元件。

18

RadioButton

允許使用者從一組選項中選擇單個選項的控制元件。

19

RichEditBox

允許使用者編輯富文字文件的控制元件,其中包含格式化文字、超連結和影像等內容。

20

ScrollViewer

一個容器控制元件,允許使用者平移和縮放其內容。

21

SearchBox

允許使用者輸入搜尋查詢的控制元件。

22

Slider

允許使用者透過沿軌道移動 Thumb 控制元件來從一系列值中進行選擇的控制元件。

23

TextBlock

顯示文字的控制元件。

24

TimePicker

允許使用者設定時間值的控制元件。

25

ToggleButton

可以在 2 個狀態之間切換的按鈕。

26

ToolTip

一個彈出視窗,顯示元素的資訊。

27

Window

提供最小化/最大化選項、標題欄、邊框和關閉按鈕的根視窗。

下面是一個示例,其中包含**SplitView** 中的不同型別的控制元件。在 XAML 檔案中,使用某些屬性和事件建立了不同的控制元件。

<Page 
   x:Class = "UWPControlsDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPControlsDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <StackPanel Margin = "20"> 
		
         <StackPanel Orientation = "Horizontal"> 
			
            <ToggleButton x:Name = "HamburgerButton" FontFamily = "Segoe MDL2 Assets"
               Content = "" Checked = "HandleCheck" Unchecked = "HandleUnchecked" 
               HorizontalAlignment = "Center"/> 
					
            <AppBarButton Icon = "Like" />
            <AppBarButton Icon = "Dislike" /> 
            <AppBarSeparator/> 
            <AppBarButton Icon = "Accept" /> 
            <AppBarButton Icon = "Add" /> 
				
         </StackPanel> 
			
         <SplitView x:Name = "splitView" DisplayMode = "Inline" 
            OpenPaneLength = "296"> 
				
            <SplitView.Pane> 
               <StackPanel> 
                  <TextBlock Text = "SplitView Pane" FontSize = "36" 
                     VerticalAlignment = "Center" HorizontalAlignment = "Center" 
                     Margin = "10"/> 
							
                  <Button Content = "Options" Margin = "10"> 
						
                     <Button.Flyout> 
                        <MenuFlyout> 
                           <MenuFlyoutItem Text = "Reset"/> 
                           <MenuFlyoutSeparator/> 
                           <MenuFlyoutItem Text = "Repeat"/> 
                           <MenuFlyoutItem Text = "Shuffle"/> 
                        </MenuFlyout> 
                     </Button.Flyout> 
							
                  </Button> 
						
               </StackPanel> 
            </SplitView.Pane> 
					
            <StackPanel>
				
               <TextBlock Text = "SplitView Content" FontSize = "36" 
                  VerticalAlignment = "Center" HorizontalAlignment = "Center" 
                  Margin = "10"/>
						
               <Border BorderThickness = "3" BorderBrush = "Red" Margin = "5"> 
                  <StackPanel Orientation = "Horizontal"> 
                     <TextBlock Text = "Hyperlink example" Margin = "5"/> 
                     <HyperlinkButton Content = "www.microsoft.com" 
                        NavigateUri = "http://www.microsoft.com"/> 
                  </StackPanel> 
               </Border> 
					
               <RelativePanel BorderBrush = "Red" BorderThickness = "2"  
                  CornerRadius = "10" Padding = "12" Margin = "5"> 
						
                  <TextBlock x:Name = "txt" Text = "Relative Panel example" 
                     RelativePanel.AlignLeftWithPanel = "True" 
                     Margin = "5,0,0,0"/> 
							
                  <TextBox x:Name = "textBox1" RelativePanel.RightOf = "btn" 
                     Margin = "5,0,0,0"/> 
							
                  <Button x:Name = "btn" Content = "Name"  
                     RelativePanel.RightOf = "txt" Margin = "5,0,0,0"/> 
							
               </RelativePanel> 
					
               <FlipView Height = "400" Margin = "10" Width = "400"> 
                  <Image Source = "Images/DSC_0104.JPG"/> 
                  <Image Source = "Images/DSC_0080.JPG"/> 
                  <Image Source = "Images/DSC_0076.JPG"/> 
                  <Image Source = "Images/thGTF7BWGW.jpg"/> 
               </FlipView>
					
            </StackPanel> 
				
         </SplitView> 
			
      </StackPanel> 
		
   </Grid> 
	
</Page> 

下面是在 C# 中的**事件**實現。

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Media;
  
// The Blank Page item template is documented at
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
 
namespace UWPControlsDemo {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
    
      public MainPage() {
         this.InitializeComponent(); 
      } 
		
      private void HandleCheck(object sender, RoutedEventArgs e) { 
         splitView.IsPaneOpen = true; 
      }
		
      private void HandleUnchecked(object sender, RoutedEventArgs e) {
         splitView.IsPaneOpen = false; 
      }
		
   }
	
} 

編譯並執行以上程式碼後,您將看到以下視窗 -

Split View Content

當您單擊左上角的漢堡包按鈕時,它將開啟/關閉**SplitView** 窗格。

Split View

在**SplitView** 窗格中,您可以看到**Flyout**、**MenuFlyout** 和**FlipView** 控制元件。

在**SplitView** 內容中,您可以看到超連結、相對面板、ViewBox 和其他按鈕和文字框控制元件。

Windows 10 開發 - 資料繫結

資料繫結是 XAML 應用程式中的一種機制,它為使用部分類的 Windows 執行時應用提供了一種簡單易用的方法來顯示和互動資料。在此機制中,資料的管理與資料在 UI 中的顯示方式完全分離。

資料繫結允許資料在 UI 元素和使用者介面上的資料物件之間流動。當建立繫結並且資料或您的業務模型發生更改時,它會自動將更新反映到 UI 元素,反之亦然。也可以繫結到頁面上的另一個元素,而不是繫結到標準資料來源。資料繫結可以是 -

  • 單向資料繫結
  • 雙向資料繫結
  • 元素繫結

單向資料繫結

在單向繫結中,資料從其源(儲存資料的物件)繫結到其目標(顯示資料的物件)。

讓我們看一下單向資料繫結的簡單示例。下面是建立了四個具有某些屬性的文字塊的 XAML 程式碼。

<Page 
   x:Class = "OneWayDataBinding.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:OneWayDataBinding" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <StackPanel Name = "Display"> 
         <StackPanel Orientation = "Horizontal" Margin = "50, 50, 0, 0"> 
            <TextBlock Text = "Name: " Margin = "10" Width = "100"/> 
            <TextBlock Margin = "10" Width = "100" Text = "{Binding Name}"/> 
         </StackPanel>
			
         <StackPanel Orientation = "Horizontal" Margin = "50,0,50,0"> 
            <TextBlock Text = "Title: " Margin = "10" Width = "100"/> 
            <TextBlock Margin = "10" Width = "200" Text = "{Binding Title}" /> 
         </StackPanel> 
			
      </StackPanel> 
   </Grid>
	
</Page>

兩個文字塊的 Text 屬性分別靜態設定為**“Name”** 和**“Title”**,而其他兩個文字塊的 Text 屬性繫結到“Name”和“Title”,它們是 Employee 類的類變數,如下所示。

using Windows.UI.Xaml.Controls;  

// The Blank Page item template is documented at  
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 
 
namespace OneWayDataBinding {
 
   /// <summary>
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
      public MainPage(){ 
         this.InitializeComponent(); 
         DataContext = Employee.GetEmployee(); 
      } 
   } 
	
   public class Employee {
      public string Name { get; set; } 
      public string Title { get; set; }  
		
      public static Employee GetEmployee() {
         var emp = new Employee() {
            Name = "Waqar Ahmed", 
            Title = "Development Manager" 
         }; 
			
         return emp; 
      } 
		
   }  
}

在**Employee 類**中,我們有變數**Name** 和**Title**,以及一個靜態方法,其中初始化**employee 物件**並將返回該 employee 物件。因此,我們繫結到屬性 Name 和 Title,但我們尚未選擇屬性所屬的物件。簡單的方法是在**MainPage** 建構函式中將物件分配給**DataContext**,我們在其中繫結其屬性。

當您執行此應用程式時,您可以在**MainWindow** 中立即看到您已成功繫結到該 Employee 物件的 Name 和 Title。

One-Way Data Binding

雙向資料繫結

在雙向繫結中,使用者可以透過使用者介面修改資料,並將這些資料更新到源中。例如,如果源在使用者檢視檢視時發生更改,則希望檢視也隨之更新。

讓我們看一下下面給出的示例,其中建立了兩個標籤、兩個文字框和一個按鈕,並設定了一些屬性和事件。

<Page 
   x:Class = "TwoWayDataBinding.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:TwoWayDataBinding" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006"
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
	
      <Grid.RowDefinitions> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "Auto" /> 
         <RowDefinition Height = "*" /> 
      </Grid.RowDefinitions> 
		
      <Grid.ColumnDefinitions> 
         <ColumnDefinition Width = "Auto" /> 
         <ColumnDefinition Width = "200" /> 
      </Grid.ColumnDefinitions> 
		
      <TextBlock Name = "nameLabel" Margin = "200,20,0,0">Name:</TextBlock> 
		
      <TextBox Name = "nameText" Grid.Column = "1" Margin = "10,20,0,0" 
         Text = "{Binding Name, Mode = TwoWay}"/>  
			
      <TextBlock Name = "ageLabel" Margin = "200,20,0,0" 
         Grid.Row = "1">Age:</TextBlock> 
			
      <TextBox Name = "ageText" Grid.Column = "1" Grid.Row = "1" Margin = "10,20,0,0" 
         Text = "{Binding Age, Mode = TwoWay}"/>
			
      <StackPanel Grid.Row = "2" Grid.ColumnSpan = "2"> 
         <Button Content = "Display" Click = "Button_Click"  
            Margin = "200,20,0,0"/> 
         <TextBlock x:Name = "txtblock" Margin = "200,20,0,0"/> 
      </StackPanel>  
		
   </Grid> 
	
</Page> 

我們可以觀察到以下內容:

  • 兩個文字框的 Text 屬性分別繫結到“Name”“Age”,它們是Person 類的類變數,如下所示。

  • Person 類中,我們只有兩個變數:Name 和 Age,並在MainWindow類中初始化了它的物件。

  • 在 XAML 程式碼中,我們繫結到屬性NameAge,但我們沒有選擇屬性所屬的物件。

  • 更簡單的方法是將一個物件分配給DataContext,我們在 C# 程式碼中繫結其屬性,如下所示,在MainWindow 建構函式中。

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
 
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  
	
namespace TwoWayDataBinding {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary>
   
   public sealed partial class MainPage : Page {
      Person person = new Person { Name = "Salman", Age = 26 }; 
		
      public MainPage() {
         this.InitializeComponent(); 
         this.DataContext = person; 
      } 
		
      private void Button_Click(object sender, RoutedEventArgs e) {
         string message = person.Name + " is " + person.Age + " years old"; 
         txtblock.Text = message; 
      } 
		
   }  
	
   public class Person {
      private string nameValue;
		
      public string Name {
         get { return nameValue; } 
         set { nameValue = value; } 
      } 
		
      private double ageValue; 
		
      public double Age {
         get { return ageValue; } 
			
         set {
            if (value != ageValue) {
               ageValue = value; 
            } 
         } 
      }
		
   } 
	
}

編譯並執行上述程式碼後,您將看到以下視窗。點選Display按鈕。

Two-Way Data Binding

讓我們更改 Name 和 Age,然後再次點選Display按鈕。

Two-Way Data Binding

您可以看到,在點選‘Display’按鈕時,文字框的文字沒有用於在TextBlock上顯示資料,而是使用了類變數。

我建議您在兩種情況下都執行上述程式碼,以便更好地理解。

元素繫結

也可以繫結到頁面上的另一個元素,而不是標準資料來源。讓我們建立一個名為ElementBinding的應用程式,其中建立了一個滑塊和一個矩形,並透過滑塊繫結矩形的寬度和高度。下面是 XAML 中的程式碼。

<Page 
   x:Class = "ElementBinding.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:ElementBinding" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <StackPanel VerticalAlignment = "Center" HorizontalAlignment = "Center">
		
         <Rectangle Height = "100" Width = "100" Fill = "SteelBlue"  
            RenderTransformOrigin = "0.5,0.5" Margin = "50"> 
				
            <Rectangle.RenderTransform> 
               <CompositeTransform ScaleX = "{Binding Value, ElementName = MySlider}" 
                  ScaleY = "{Binding Value, ElementName = MySlider}"/> 
            </Rectangle.RenderTransform> 
				
         </Rectangle>
			
         <Slider Minimum = ".5" Maximum = "2.0" StepFrequency = ".1"  
            x:Name = "MySlider" /> 
				
      </StackPanel> 
   </Grid> 
	
</Page> 

編譯並執行上述程式碼後,您將看到以下視窗。

Element Binding

使用滑塊,您可以更改矩形的大小,如下所示。

Element Binding

Windows 10 開發 - XAML 效能

應用程式的效能非常重要,例如應用程式啟動速度或導航到顯示下一個內容的速度等。

應用程式的效能可能會受到許多因素的影響,包括 XAML 渲染引擎解析應用程式中所有 XAML 程式碼的能力。XAML 是一個非常強大的 UI 建立工具,但可以透過使用 Windows 10 應用程式中現在可用的新技術使其更加強大。

例如,在您的應用程式中,有些內容您希望在頁面載入時顯示,然後以後不再需要。在啟動時,您可能也不需要載入所有 UI 元素。

在 Windows 10 應用程式中,XAML 中添加了一些新功能,這些功能提高了 XAML 的效能。

任何通用 Windows 應用程式的效能都可以透過以下技術得到改進:

  • 漸進式渲染
  • 延遲載入

漸進式渲染

在 Windows 10 中,XAML 中引入了兩個新的非常酷的功能。它們是:

x:Bind

這是 XAML 中引入的一種用於繫結的新語法,其工作方式與Binding語法幾乎相同。x:Bind有兩個主要區別:它提供編譯時語法驗證和更好的效能。

X:Phase

它提供了優先順序處理資料模板內 XAML 控制元件渲染的功能。每個 UI 元素只能指定一個階段。如果是這樣,它將應用於元素上的所有繫結。如果未指定階段,則假定為階段 0。

在通用 Windows 平臺 (UWP) 應用程式中,這兩個新功能提供了效能改進。它也可以用於遷移到 Windows 10 的現有 Windows 8.x 應用程式。

下面是一個示例,其中使用x:Bind關鍵字將員工物件與GridView繫結。

<Page 
   x:Class = "XAMLPhase.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:local = "using:XAMLPhase" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <GridView Name = "Presidents" ItemsSource = "{Binding}" Height = "300" 
         Width = "400" Margin = "50"> 
			
         <GridView.ItemTemplate> 
            <DataTemplate x:DataType = "local:Employee"> 
				
               <StackPanel Orientation = "Horizontal" Margin = "2"> 
                  <TextBlock Text = "{x:Bind Name}" Width = "95" Margin = "2" /> 
                  <TextBlock Text = "{x:Bind Title}" Width = "95" Margin = "2"  
                     x:Phase = "1"/> 
               </StackPanel> 
					
            </DataTemplate> 
         </GridView.ItemTemplate>
			
      </GridView> 
		
   </Grid> 
	
</Page>

在上面的 XAML 程式碼中,x:Phase = "1"與 Title 一起定義。因此,在第一階段,將渲染Name,然後渲染Title

下面是 C# 中Employee 類的實現。

using System.Collections.ObjectModel; 
using System.ComponentModel; 
using System.Runtime.CompilerServices; 
using Windows.UI.Xaml.Controls;
  
// The Blank Page item template is documented at
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 
	
namespace XAMLPhase {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
      public MainPage() {
         this.InitializeComponent(); 
         DataContext = Employee.GetEmployees(); 
      } 
   } 
	
   public class Employee : INotifyPropertyChanged {
      private string name; 
		
      public string Name {
         get { return name; } 
			
         set {
            name = value; 
            RaiseProperChanged(); 
         } 
      } 
		
      private string title; 
		
      public string Title {
         get { return title; }
			
         set {
            title = value; 
            RaiseProperChanged(); 
         } 
      }
		
      public static Employee GetEmployee() {
       
         var emp = new Employee() {
            Name = "Waqas", 
            Title = "Software Engineer" 
         };  
			
         return emp; 
      } 
		
      public event PropertyChangedEventHandler PropertyChanged;
		
      private void RaiseProperChanged( 
         [CallerMemberName] string caller = "") {
			
         if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(caller)); 
         } 
			
      } 
		
      public static ObservableCollection<Employee> GetEmployees() {
         var employees = new ObservableCollection<Employee>(); 
			
         employees.Add(new Employee() { Name = "Ali", Title = "Developer" }); 
         employees.Add(new Employee() { Name = "Ahmed", Title = "Programmer" }); 
         employees.Add(new Employee() { Name = "Amjad", Title = "Desiner" }); 
         employees.Add(new Employee() { Name = "Waqas", Title = "Programmer" }); 
         employees.Add(new Employee() { Name = "Bilal", Title = "Engineer" }); 
         employees.Add(new Employee() { Name = "Waqar", Title = "Manager" }); 
			
         return employees; 
      } 
		
   }
	
}

執行上述程式碼後,您將看到以下視窗。

XAML Phase

X:Phasex:Bind一起用於增量渲染ListViewGridView項,並改善平移體驗。

延遲載入

延遲載入是一種技術,可用於透過減少應用程式啟動時的 XAML UI 元素數量來最大程度地減少啟動載入時間。如果您的應用程式包含 30 個 UI 元素,並且使用者在啟動時不需要所有這些元素,那麼所有不需要的元素都可以透過延遲來節省一些載入時間。

x:DeferLoadStrategy = "Lazy"延遲建立元素及其子元素,這會減少啟動時間,但會略微增加記憶體使用量。

可以透過使用元素上定義的名稱呼叫FindName來實現/建立延遲元素。

建立延遲元素後,將發生以下幾件事:

  • 將引發元素上的 Loaded 事件。

  • 將評估元素上的任何繫結。

  • 如果應用程式已註冊以接收包含延遲元素的屬性上的屬性更改通知,則將引發該通知。

下面是一個示例,其中x:DeferLoadStrategy = "Lazy"用於包含四個文字塊的網格,並且在應用程式啟動時不會載入,直到您載入它為止。

<Page 
   x:Class = "UWPDeferredLoading.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPDeferredLoading" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <Grid x:Name = "DeferredGrid" x:DeferLoadStrategy = "Lazy" Margin = "50"> 
         <Grid.RowDefinitions> 
            <RowDefinition Height = "Auto" /> 
            <RowDefinition Height = "Auto" /> 
         </Grid.RowDefinitions> 
			
         <Grid.ColumnDefinitions> 
            <ColumnDefinition Width = "Auto" /> 
            <ColumnDefinition Width = "Auto" /> 
         </Grid.ColumnDefinitions>
			
         <TextBlock Height = "100" Width = "100" Text = "TextBlock 1" Margin = "0,0,4,4" /> 
			
         <TextBlock Height = "100" Width = "100" Text = "TextBlock 2" 
            Grid.Column = "1" Margin = "4,0,0,4" /> 
				
         <TextBlock Height = "100" Width = "100" Text = "TextBlock 3" 
            Grid.Row = "1" Margin = "0,4,4,0" /> 
				
         <TextBlock Height = "100" Width = "100" Text = "TextBlock 4" 
            Grid.Row = "1" Grid.Column = "1" Margin = "4,4,0,0" /> 
      </Grid> 
		
      <Button x:Name = "RealizeElements" Content = "Show Elements"  
         Click = "RealizeElements_Click" Margin = "50"/> 
			
   </Grid>   
	
</Page> 

以下程式是點選事件的實現,其中網格在應用程式主頁面載入。

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
 
// The Blank Page item template is documented at
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  
	
namespace UWPDeferredLoading {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
      public MainPage() {
         this.InitializeComponent(); 
      }  
		
      private void RealizeElements_Click(object sender, RoutedEventArgs e) {
         this.FindName("DeferredGrid"); // This will realize the deferred grid 
      } 
		
   } 
	
}

編譯並執行上述程式碼後,您只會看到一個按鈕。Textblocks在啟動時不會載入。

UWP Different Loading

現在,當您點選Show Elements按鈕時,它將載入文字塊,這將提高應用程式的啟動效能。

UWP Different Loading Exe

Windows 10 開發 - 自適應設計

在 Windows 10 中,通用 Windows 平臺 (UWP) 應用程式現在可以在許多裝置系列上執行,例如:

  • 桌面裝置系列 - 平板電腦、筆記型電腦、PC

  • 移動裝置系列 - Windows 手機、平板手機

  • 物聯網裝置系列 - 可穿戴裝置或家用電器等緊湊型裝置

  • 團隊裝置系列 - Surface Hub

每個裝置系列都有其自己的螢幕和視窗大小。那麼如何設計一個應用程式,使其在多個螢幕尺寸和不同的輸入方法差別很大的裝置上提供良好的使用者體驗呢?

為多個裝置系列設計應用程式需要一些額外的考慮、計劃和設計。Windows 10 UWP 提供了一套內建功能和通用構建塊,使為多個裝置設計以及跨平臺控制元件支援的不同螢幕和視窗大小自動縮放變得更加容易。

新內建功能

以下是開發人員在建立 UWP 應用程式時可以使用的新功能。這些功能是自動且免費的。

有效畫素和平臺縮放

當您的 UWP 應用程式在 Windows 10 支援的任何裝置上執行時,則:

  • 系統使用一種演算法來規範控制元件、字型和其他 UI 元素在當前執行的裝置螢幕上的顯示方式。

  • 縮放演算法控制觀看距離和螢幕密度(每英寸畫素數),以針對假定大小(而不是物理大小)進行最佳化。

  • 縮放演算法確保 10 英尺外的 Surface Hub 上的 36 px 字型與幾英寸外的 5 英寸手機上的 36 px 字型對使用者來說同樣易讀。

Scaling Algorithm

通用輸入和智慧互動

通用 Windows 平臺內建了智慧互動輸入系統,該系統可以理解所有裝置的輸入。例如,當您在應用程式中設計點選互動時,您無需知道點選來自實際滑鼠點選還是手指點選。系統會自動為您完成。

通用構建塊

有一些有價值的構建塊,使在通用 Windows 平臺 (UWP) 中為多個裝置系列設計應用程式變得更加容易。

通用控制元件

UWP 提供了一組通用控制元件,這些控制元件保證可以在所有 Windows 10 裝置上正常工作。

  • 此“通用控制元件”列表包含單選按鈕、組合框和文字框等常用控制元件。

  • 它還包含一些複雜的控制元件,例如網格檢視列表檢視,這些控制元件可以從資料流和模板生成專案列表。

通用樣式

UWP 應用程式自動獲得一組預設樣式,為您提供以下功能:

  • 一組樣式,可以自動為您的應用程式提供淺色或深色主題。

  • 互動的預設動畫。

  • 對高對比度模式的自動支援。

  • 對其他語言的自動支援。我們的預設樣式會自動為 Windows 支援的每種語言選擇正確的字型。您甚至可以在同一個應用程式中使用多種語言,並且它們將正確顯示。

Windows 10 開發 - 自適應 UI

通用 Windows 平臺 (UWP) 應用程式可以在許多不同的裝置上執行,並且每個裝置都有其自己的輸入形式、螢幕解析度、DPI 密度和其他獨特特性。

在 Windows 10 中,藉助新的通用控制元件、佈局面板和工具,您可以輕鬆地使您的 UI 適應應用程式可能執行的裝置。例如,當您的 UWP 應用程式在臺式電腦、移動裝置或平板電腦上執行時,您可以調整 UI 以利用不同的螢幕解析度、螢幕尺寸和 DPI 密度。

在 Windows 10 中,您可以使用以下功能輕鬆地將 UI 定向到多個裝置:

  • 您可以透過使用通用控制元件和佈局面板來增強不同螢幕解析度和螢幕尺寸的 UI。

  • 通用輸入處理允許您透過觸控板、筆、滑鼠、鍵盤或控制器(例如 Microsoft Xbox 控制器)接收輸入。

  • 藉助工具,您可以設計能夠適應不同螢幕解析度的應用程式 UI。

  • 自適應縮放會根據裝置之間的解析度和 DPI 差異進行調整。

在 Windows 10 中,您可以輕鬆地以任何您想要的方式排列、調整大小和定位應用程式。它還為使用者提供了一種靈活性,讓他們可以按照自己的意願使用您的應用程式。在 Windows 10 中,有各種方法可以在您的 UWP 應用程式中實現響應式技術,因此無論螢幕或視窗大小如何,它都看起來很棒。

VisualStateManager

在 Windows 10 中,VisualStateManager 類具有兩種新的機制,藉助這些機制,您可以在 UWP 應用程式中實現響應式設計。新的 VisualState.StateTriggers 允許開發人員檢查某些條件(例如視窗高度或視窗寬度),然後 VisualState.Setters API 定義對這些特定條件的視覺狀態。

讓我們看一下下面給出的示例,其中在堆疊面板中添加了一些控制元件。

<Page 
   x:Class = "UWPAdaptiveUI.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPAdaptiveUI" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <VisualStateManager.VisualStateGroups>
		
         <VisualStateGroup>
			
            <VisualState>
				
               <VisualState.StateTriggers>
                  <!-- VisualState to be triggered when window 
                     width is >=720 effective pixels. -->
                  <AdaptiveTrigger MinWindowWidth = "720" />
               </VisualState.StateTriggers>
					
               <VisualState.Setters>
                  <Setter Target = "myPanel.Orientation" Value = "Horizontal" />
               </VisualState.Setters>
					
            </VisualState>
				
         </VisualStateGroup>
			
      </VisualStateManager.VisualStateGroups>
		
      <StackPanel x:Name = "myPanel" Orientation = "Vertical">
		
         <TextBlock Text = "Windows 10 Tutorials: Text block 1. " 
            Style = "{ThemeResource BodyTextBlockStyle}"/>
				
         <TextBlock Text = "Windows 10 Tutorials: Text block 2. " 
            Style = "{ThemeResource BodyTextBlockStyle}"/>
				
         <TextBlock Text = "Windows 10 Tutorials: Text block 3. " 
            Style = "{ThemeResource BodyTextBlockStyle}"/>
				
      </StackPanel> 
		
   </Grid>
	
</Page>

現在 VisualStateManager 將根據視窗的寬度調整堆疊面板的方向。如果寬度 >= 720,則方向將變為水平,否則將保持垂直。編譯並執行上述程式碼後,您將看到以下視窗,其中包含三個按垂直順序排列的文字塊。

Visual State Manager

讓我們調整上述視窗的寬度,您將看到以下視窗 -

Visual State Manager Resize

現在您可以看到文字塊是按水平順序排列的。

RelativePanel

RelativePanel 可用於透過表達元素之間的空間關係來佈局 UI 元素。讓我們舉一個在相對面板中建立一些矩形的例子。

<Page 
   x:Class = "UWPAdaptiveUI.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPAdaptiveUI" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
	
      <VisualStateManager.VisualStateGroups> 
		
         <VisualStateGroup> 
			
            <VisualState> 
				
               <VisualState.StateTriggers> 
                  <AdaptiveTrigger MinWindowWidth = "720" /> 
               </VisualState.StateTriggers> 
					
               <VisualState.Setters> 
                  <Setter Target = "GreenRect.(RelativePanel.RightOf)"
                     Value = "BlueRect" /> 
                  <Setter Target = "GreenRect.(RelativePanel.AlignRightWithPanel)" 
                     Value = "True" /> 
               </VisualState.Setters> 
					
            </VisualState> 
				
         </VisualStateGroup>
			
      </VisualStateManager.VisualStateGroups>
		
      <RelativePanel BorderBrush = "Gray" BorderThickness = "10"> 
         <Rectangle x:Name = "RedRect" Fill = "Red" MinHeight = "100" 
            MinWidth = "100"/> 
				
         <Rectangle x:Name = "BlueRect" Fill = "Blue" MinHeight = "100" 
            MinWidth = "100" RelativePanel.RightOf = "RedRect" /> 
				
         <!-- Width is not set on the green and yellow rectangles. 
            It's determined by the RelativePanel properties. --> 
				
         <Rectangle x:Name = "GreenRect" Fill = "Green" MinHeight = "100" 
            RelativePanel.Below = "BlueRect" RelativePanel.AlignLeftWith = "RedRect" 
            RelativePanel.AlignRightWith = "BlueRect"/> 
				
         <Rectangle Fill = "Yellow" MinHeight = "100" RelativePanel.Below = "GreenRect" 
            RelativePanel.AlignLeftWith = "BlueRect"
            RelativePanel.AlignRightWithPanel = "True"/> 
				
      </RelativePanel> 
		
   </Grid> 
	
</Page> 

編譯並執行上述程式碼後,您將看到以下視窗。

UWP Adaptive UI

調整上述視窗大小時,您會看到綠色矩形現在已調整到藍色矩形左側的頂行,如下所示。

UWP Adaptive UI Rectangle

Windows 10 開發 - 自適應程式碼

在本章中,我們將演示如何使您的應用程式適用於 Windows 10 支援的不同裝置。我們已經瞭解瞭如何採用您的 UI 以及 UWP 應用程式中使用的所有技巧、技術和控制元件。

現在,我們將學習如何採用您的程式碼,因為

  • 應用程式程式碼在所有裝置上都不相同。

  • 使用的 API,特別是針對 Xbox 的 API,在移動裝置上將不可用。HoloLens 等也是如此。

Windows Devices

自適應程式碼可以根據條件啟用您的應用程式,並且僅在特定裝置系列和/或特定版本的平臺/擴充套件 API 上執行時才執行程式碼。

編寫程式碼

在 Windows 10 中,您可以使用 C++、C#、Visual Basic 或 JavaScript 在 Visual Studio 中實現 UWP 應用程式。

  • 使用 C# 和 Visual Basic,您可以使用 XAML 進行 UI 設計。

  • 使用 C++,您可以使用 DirectX 而不是使用 XAML。

  • 對於 JavaScript,您可以使用 HTML 作為您的表示層,它是一個跨平臺的 Web 標準。

Windows Core API 在所有裝置上的執行方式相同,其中包含程式碼和 UI 所需的大多數功能。但是,對於針對特定裝置系列的程式碼和 UI,您需要使用自適應程式碼和自適應 UI。

呼叫目標裝置系列未實現的 API -

UI 可以輕鬆適應不同的螢幕,但不同的裝置系列不僅具有不同的螢幕尺寸,而且還有更多其他方面。

  • 例如,手機有一些硬體按鈕,如返回鍵和相機鍵,這些按鈕在其他裝置(如 PC)上可能不可用。

  • 預設情況下,核心 API 包含適用於所有裝置的大多數功能,但可以透過在 UWP 應用程式中引用擴充套件 SDK(就像外部程式集一樣)來使用特定於裝置的功能。

要新增應用程式中需要的任何特定擴充套件 SDK,請按照以下步驟操作 -

  • 右鍵單擊引用

  • 選擇“新增引用...”。將開啟以下對話方塊。

Add References Manager
  • 新增擴充套件就像新增專案引用一樣簡單。

  • 現在,您可以從列表中新增任何擴充套件 SDK,其中包含桌面擴充套件、IoT 擴充套件和移動擴充套件等。

桌面和移動擴充套件是兩個最常見的平臺擴充套件 SDK。例如,移動擴充套件啟用了使用硬體相機按鈕所需的 API。

您可以使用Windows.Foundation.Metadata.ApiInformation 類方法檢查裝置功能,如果當前裝置支援該型別,則該方法將返回布林輸出。例如,您可以使用如下程式碼啟用您的 Windows 應用來使用相機按鈕 -

bool isHardwareButtonsAPIPresent = 
   Windows.Foundation.Metadata.ApiInformation.
   IsTypePresent("Windows.Phone.UI.Inpu t.HardwareButtons");  
		
if (isHardwareButtonsAPIPresent) { 
   Windows.Phone.UI.Input.HardwareButtons.CameraPressed += HardwareButtons_CameraPressed; 
} 

僅當裝置上啟用了移動擴充套件 SDK 時,才會執行手機相機按鈕程式碼。類似地,您還可以使用IsEventPresentIsMethodPresentIsPropertyPresent代替IsTypePresent來檢查當前 API 版本中的任何特定事件、方法或屬性,如下所示。

bool isHardwareButtons_CameraPressedAPIPresent = 
   Windows.Foundation.Metadata.ApiInformation.IsEventPresent 
   ("Windows.Phone.UI.Input.HardwareButtons", "CameraPressed");

UWP 中的 Win32 API

用 C++/CX 編寫的通用 Windows 平臺 (UWP) 應用程式或 Windows 執行時元件可以訪問 Win32 API,這些 API 現在也是 UWP 的一部分。所有 Windows 10 裝置系列都可以透過將應用程式與Windowsapp.lib連結來實現 Win32 API。

Windowsapp.lib是一個“傘形”庫,提供 UWP API 的匯出。連結到Windowsapp.lib將向您的應用新增對所有 Windows 10 裝置系列中存在的dll的依賴項。

讓我們來看一個簡單的例子,其中應用程式同時針對桌面和手機。因此,當應用程式在桌面上執行時,它不會顯示狀態列,但當同一應用程式在手機上執行時,它將顯示狀態列。

以下是新增不同控制元件的 XAML 程式碼。

<Page 
   x:Class = "UWPAdoptiveCode.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPAdoptiveCode" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008"
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  

   <Page.Background> 
      <SolidColorBrush Color = "Green"/> 
   </Page.Background>
	
   <Page.BottomAppBar> 
      <CommandBar x:Name = "commandBar" > 
         <AppBarButton Icon = "Accept" Label = "appbarbutton"/> 
         <AppBarButton Icon = "Cancel" Label = "appbarbutton"/> 
      </CommandBar> 
   </Page.BottomAppBar>
	
   <Grid Background = "AliceBlue"> 
	
      <VisualStateManager.VisualStateGroups> 
		
         <VisualStateGroup> 
			
            <VisualState> 
               <VisualState.StateTriggers> 
                  <local:DeviceFamilyTrigger DeviceFamily = "Desktop" /> 
               </VisualState.StateTriggers> 
					
               <VisualState.Setters> 
                  <Setter Target = "StatusBarControls.Visibility" 
                     Value = "Collapsed"/> 
               </VisualState.Setters>  
					
            </VisualState> 
				
         </VisualStateGroup> 
			
      </VisualStateManager.VisualStateGroups> 
		
      <StackPanel HorizontalAlignment = "Left" Margin = "75,164,0,0"
         VerticalAlignment = "Top" > 
			
         <RadioButton x:Name = "ShowAppBarRadioButton" Content = "Show AppBar"
            HorizontalAlignment = "Stretch" VerticalAlignment = "Stretch"
            IsChecked = "True" Checked = "RadioButton_Checked"/>
				
         <RadioButton x:Name = "ShowOpaqueAppBarRadioButton" 
            Content = "Show Transparent AppBar" HorizontalAlignment = "Stretch"
            VerticalAlignment = "Stretch" Checked = "RadioButton_Checked"/> 
				
         <RadioButton x:Name = "HideAppBarRadioButton" Content = "Hide AppBar"
            HorizontalAlignment = "Stretch" VerticalAlignment = "Stretch" 
            Checked = "RadioButton_Checked"/>
				
      </StackPanel> 
		
      <StackPanel x:Name = "StatusBarControls" Orientation = "Vertical" 
         Margin = "75,350,0,0" Visibility = "Visible">
			
         <CheckBox x:Name = "StatusBarBackgroundCheckBox" 
            Content = "Set StatusBar Background"
            Checked = "StatusBarBackgroundCheckBox_Checked" 
            Unchecked = "StatusBarBackgroundCheckBox_Unchecked"/>
				
         <CheckBox x:Name = "StatusBarHiddenCheckBox" 
            Content = "Set StatusBar Hidden" Checked = "StatusBarHiddenCheckBox_Checked"
            Unchecked = "StatusBarHiddenCheckBox_Unchecked"/> 
				
      </StackPanel> 
		
   </Grid> 
	
</Page>	

以下是不同事件的 C# 實現。

using Windows.UI; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;  

// The Blank Page item template is documented at
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace UWPAdoptiveCode { 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page { 
     
      private Color? DefaultTitleBarButtonsBGColor; 
      private Color? DefaultTitleBarBGColor;
		
      public MainPage() {
         this.InitializeComponent();
			
         //Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().
            VisibleBoundsCh anged += MainPage_VisibleBoundsChanged;
				
         var viewTitleBar = Windows.UI.ViewManagement.ApplicationView.
            GetForCurrentView().TitleBar; 
				
         DefaultTitleBarBGColor = viewTitleBar.BackgroundColor; 
         DefaultTitleBarButtonsBGColor = viewTitleBar.ButtonBackgroundColor; 
      } 
		
      private void RadioButton_Checked(object sender, RoutedEventArgs e) {
        
         // Bottom AppBar shows on Desktop and Mobile 
         if (ShowAppBarRadioButton != null) {
			  
            if (ShowAppBarRadioButton.IsChecked.HasValue &&
               (ShowAppBarRadioButton.IsChecked.Value == true)) {
                 commandBar.Visibility = Windows.UI.Xaml.Visibility.Visible; 
                 commandBar.Opacity = 1; 
            } else {
               commandBar.Visibility = Windows.UI.Xaml.Visibility.Collapsed; 
            } 
         } 
			
         if (ShowOpaqueAppBarRadioButton != null) {
             
            if (ShowOpaqueAppBarRadioButton.IsChecked.HasValue &&
               (ShowOpaqueAppBarRadioButton.IsChecked.Value == true)){ 
                  commandBar.Visibility = Windows.UI.Xaml.Visibility.Visible; 
                  commandBar.Background.Opacity = 0; 
            } else{ 
               commandBar.Background.Opacity = 1; 
            } 
         } 
			
      } 
		
      private void StatusBarHiddenCheckBox_Checked(object sender, RoutedEventArgs e){
        
         // StatusBar is Mobile only 
         if (Windows.Foundation.Metadata.ApiInformation.
            IsTypePresent("Windows.UI.ViewManag ement.StatusBar")){ 
               var ignore = Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync(); 
         } 
      } 
		
      private void StatusBarHiddenCheckBox_Unchecked(object sender, RoutedEventArgs e){
	  
         // StatusBar is Mobile only 
         if (Windows.Foundation.Metadata.ApiInformation.
            IsTypePresent("Windows.UI.ViewManag ement.StatusBar")){
               var ignore = Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync(); 
         } 
      }  
		
      private void StatusBarBackgroundCheckBox_Checked(object sender, RoutedEventArgs e){
       
         // StatusBar is Mobile only 
         if (Windows.Foundation.Metadata.ApiInformation.
            IsTypePresent("Windows.UI.ViewManag ement.StatusBar")){ 
				
               Windows.UI.ViewManagement.StatusBar.GetForCurrentView().
                  BackgroundColor = Windows.UI.Colors.Blue; 
					
               Windows.UI.ViewManagement.StatusBar.GetForCurrentView().
                   BackgroundOpacity = 1; 
         } 
      }  
		
      private void StatusBarBackgroundCheckBox_Unchecked(object sender, RoutedEventArgs e){
         
         // StatusBar is Mobile only 
         if (Windows.Foundation.Metadata.ApiInformation.
            IsTypePresent("Windows.UI.ViewManag ement.StatusBar")){
               Windows.UI.ViewManagement.StatusBar.GetForCurrentView().
                  BackgroundOpacity = 0; 
         } 
      } 
		
   } 
	
   public class DeviceFamilyTrigger : StateTriggerBase{
    
      //private variables 
      private string _deviceFamily;
	  
      //Public property 
      public string DeviceFamily {
         
         get {
            return _deviceFamily; 
         } 
         set{
            _deviceFamily = value; 
            var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.
               GetForCurrentView().Qua lifierValues; 
					
            if (qualifiers.ContainsKey("DeviceFamily")) 
               SetActive(qualifiers["DeviceFamily"] == _deviceFamily); 
            else 
               SetActive(false); 
         } 
      } 
   } 
} 

編譯並在手機上執行上述程式碼後,您將看到以下視窗。

Adaptive Code Execute

您可以使用複選框更改狀態列的背景顏色,如影像所示。

Adaptive Code Execute Status

您還可以隱藏狀態列。

Adaptive Code Execute Status Bar

現在,當您在桌面裝置上運行同一應用程式時,您將看到以下視窗,其中狀態列和特定於狀態列的複選框不可見。

Adaptive Code Execute Status Bar checkbox

Windows 10 開發 - 檔案管理

在任何應用程式中,資料都是最重要的內容之一。如果您是.net開發人員,您可能瞭解隔離儲存,並且通用 Windows 平臺 (UWP) 應用程式也遵循相同的概念。

檔案位置

這些是您的應用程式可以訪問資料的區域。應用程式包含一些特定於該應用程式的私有區域,其他應用程式無法訪問,但還有許多其他區域,您可以在其中將資料儲存和儲存到檔案中。

File Location

以下是每個資料夾的簡要說明。

序號 資料夾和說明
1

應用包資料夾

包管理器將所有與應用程式相關的檔案安裝到應用包資料夾中,並且應用程式只能從此資料夾讀取資料。

2

本地資料夾

應用程式將本地資料儲存到本地資料夾中。它可以儲存的資料量取決於儲存裝置上的限制。

3

漫遊資料夾

與應用程式相關的設定和屬性儲存在漫遊資料夾中。其他裝置也可以從此資料夾訪問資料。它的大小限制為每個應用程式 100KB。

4

臨時資料夾

用於臨時儲存,並且不保證在應用程式再次執行時它仍然可用。

5

釋出者共享

同一釋出者的所有應用程式的共享儲存。它在應用清單中宣告。

6

憑據保管庫

用於安全儲存密碼憑據物件。

7

OneDrive

OneDrive 是隨您的 Microsoft 帳戶提供的免費線上儲存。

8

將資料儲存在雲中。

9

已知資料夾

這些資料夾已經是已知資料夾,例如“我的圖片”、“影片”和“音樂”。

10

可移動儲存

USB 儲存裝置或外部硬碟驅動器等。

檔案處理 API

在 Windows 8 中,引入了新的檔案處理 API。這些 API 位於Windows.StorageWindows.Storage.Streams名稱空間中。您可以使用這些 API 而不是System.IO.IsolatedStorage名稱空間。透過使用這些 API,將更容易將您的 Windows Phone 應用移植到 Windows 應用商店,並且您可以輕鬆地將您的應用程序升級到 Windows 的未來版本。

要訪問本地、漫遊或臨時資料夾,您需要呼叫這些 API -

StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
StorageFolder roamingFolder = ApplicationData.Current.RoamingFolder; 
StorageFolder tempFolder = ApplicationData.Current.TemporaryFolder; 

要在本地資料夾中建立新檔案,請使用以下程式碼 -

StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
StorageFile textFile = await localFolder.CreateFileAsync(filename, 
   CreationCollisionOption.ReplaceExisting);

這是開啟新建立的檔案並在該檔案中寫入一些內容的程式碼。

using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite)) { 
	
   using (DataWriter textWriter = new DataWriter(textStream)){
      textWriter.WriteString(contents); 
      await textWriter.StoreAsync(); 
   } 
		
}

您可以從本地資料夾中再次開啟同一檔案,如以下程式碼所示。

using (IRandomAccessStream textStream = await textFile.OpenReadAsync()) { 

   using (DataReader textReader = new DataReader(textStream)){
      uint textLength = (uint)textStream.Size; 
      await textReader.LoadAsync(textLength); 
      contents = textReader.ReadString(textLength); 
   } 
	
}

要了解資料讀取和寫入的工作原理,讓我們來看一個簡單的例子。以下是新增不同控制元件的 XAML 程式碼。

<Page
   x:Class = "UWPFileHandling.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPFileHandling" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
	
      <Button x:Name = "readFile" Content = "Read Data From File"  
         HorizontalAlignment = "Left" Margin = "62,518,0,0"  
         VerticalAlignment = "Top" Height = "37" Width = "174"  
         Click = "readFile_Click"/> 
			
      <TextBox x:FieldModifier = "public" x:Name = "textBox"  
         HorizontalAlignment = "Left" Margin = "58,145,0,0" TextWrapping = "Wrap"  
         VerticalAlignment = "Top" Height = "276" Width = "245"/>.
			
      <Button x:Name = "writeFile" Content = "Write Data to File"
         HorizontalAlignment = "Left" Margin = "64,459,0,0"  
         VerticalAlignment = "Top" Click = "writeFile_Click"/>
			
      <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"  
         Margin = "386,149,0,0" TextWrapping = "Wrap"  
         VerticalAlignment = "Top" Height = "266" Width = "250"  
         Foreground = "#FF6231CD"/> 
			
   </Grid> 
	 
</Page>

以下是不同事件的 C# 實現,以及用於讀取和寫入文字檔案資料的FileHelper類的實現。

using System; 
using System.IO; 
using System.Threading.Tasks; 

using Windows.Storage; 
using Windows.Storage.Streams; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;
  
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 
 
namespace UWPFileHandling {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public partial class MainPage : Page {
      const string TEXT_FILE_NAME = "SampleTextFile.txt"; 
		
      public MainPage(){ 
         this.InitializeComponent(); 
      }  
		
      private async void readFile_Click(object sender, RoutedEventArgs e) {
         string str = await FileHelper.ReadTextFile(TEXT_FILE_NAME); 
         textBlock.Text = str; 
      }
		
      private async void writeFile_Click(object sender, RoutedEventArgs e) {
         string textFilePath = await FileHelper.WriteTextFile(TEXT_FILE_NAME, textBox.Text); 
      }
		
   } 
	
   public static class FileHelper {
     
      // Write a text file to the app's local folder. 
	  
      public static async Task<string> 
         WriteTextFile(string filename, string contents) {
         
         StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
         StorageFile textFile = await localFolder.CreateFileAsync(filename,
            CreationCollisionOption.ReplaceExisting);  
				
         using (IRandomAccessStream textStream = await 
            textFile.OpenAsync(FileAccessMode.ReadWrite)){ 
             
               using (DataWriter textWriter = new DataWriter(textStream)){ 
                  textWriter.WriteString(contents); 
                  await textWriter.StoreAsync(); 
               } 
         }  
			
         return textFile.Path; 
      }
		
      // Read the contents of a text file from the app's local folder.
	  
      public static async Task<string> ReadTextFile(string filename) {
         string contents;  
         StorageFolder localFolder = ApplicationData.Current.LocalFolder; 
         StorageFile textFile = await localFolder.GetFileAsync(filename);
			
         using (IRandomAccessStream textStream = await textFile.OpenReadAsync()){
             
            using (DataReader textReader = new DataReader(textStream)){
               uint textLength = (uint)textStream.Size; 
               await textReader.LoadAsync(textLength); 
               contents = textReader.ReadString(textLength); 
            }
				
         }
			
         return contents; 
      } 
   } 
} 

編譯並執行上述程式碼後,您將看到以下視窗。

File Management Execute

現在,您在文字框中寫入內容並單擊“將資料寫入檔案”按鈕。程式將資料寫入本地資料夾中的文字檔案。如果您單擊“從檔案讀取資料”按鈕,程式將從位於本地資料夾中的同一文字檔案中讀取資料,並將其顯示在文字塊上。

File Management Read Write

Windows 10 開發 - SQLite 資料庫

在許多應用程式中,某些型別的資料彼此之間存在某種關係。這些難以儲存在檔案中的資料型別可以儲存在資料庫中。

如果您熟悉任何應用程式中的 SQL Server 或 Oracle 資料庫等資料庫型別,那麼理解SQLite 資料庫非常容易。

什麼是 SQLite?

SQLite 是一個軟體庫,它實現了自包含、無伺服器、零配置、事務性 SQL 資料庫引擎。

重要功能包括 -

  • SQLite 是世界上部署最廣泛的資料庫引擎。

  • SQLite 的原始碼是開源的。

  • 由於其可移植性和較小的佔用空間,它對遊戲和移動應用程式開發產生了重大影響。

SQLite 的優勢

以下是 SQLite 的優勢 -

  • 它是一個非常輕量級的資料庫。
  • 它是平臺獨立的,可在所有平臺上執行。
  • 它具有較小的記憶體佔用空間。
  • 它是可靠的。
  • 無需任何設定和安裝。
  • 它沒有任何依賴項。

要在您的通用 Windows 平臺 (UWP) 應用程式中使用SQLite,您需要按照以下步驟操作。

  • 使用名稱UWPSQLiteDemo建立一個新的通用 Windows 空白應用。

  • 轉到工具選單,然後選擇擴充套件和更新。將開啟以下對話方塊。

UWP SQLite Demo
  • 選擇擴充套件和更新後,將開啟以下視窗。
UWP SQLite Extensions and Updates
  • 現在選擇聯機選項,然後從左側窗格中搜索 SQLite。

  • 下載並安裝適用於通用應用平臺的 SQLite。

  • 現在,再次轉到工具選單,然後選擇NuGet 包管理器 > 包管理器控制檯選單選項,如下所示。

UWP SQLite Manage Console
  • 在包管理器控制檯中寫入以下命令,然後按 Enter 執行此命令 -

Install-Package SQLite.Net-PCL 

UWP SQLite Console Command
  • 現在,在解決方案資源管理器中右鍵單擊引用,然後選擇新增引用

UWP SQLite Add References
  • 將開啟以下對話方塊。
UWP SQLite Dialog
  • 通用 Windows下的左側窗格中選擇擴充套件,在中間窗格中選中適用於通用應用平臺的 SQLite,然後單擊確定。

  • 現在,您已準備好開始在 UWP 應用程式中使用 SQLite 了。

您可以使用以下程式碼建立資料庫。

string path = Path.Combine(Windows.Storage.ApplicationData.
   Current.LocalFolder.Path, "db.sqlite"); 

SQLite.Net.SQLiteConnection conn = new SQLite.Net.SQLiteConnection(new 
   SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);

要建立表格,您需要使用表名物件呼叫CreateTable方法。

conn.CreateTable<Customer>(); 

您可以使用以下程式碼將資料插入到您的表格中。

conn.Insert(new Customer(){
   Name = textBox.Text, 
   Age = textBox1.Text 
});

以下是從表格中檢索資料的程式碼。

var query = conn.Table<Customer>(); 
string id = ""; 
string name = ""; 
string age = ""; 
 
foreach (var message in query) { 
   id = id + " " + message.Id; 
   name = name + " " + message.Name; 
   age = age + " " + message.Age; 
}

讓我們透過一個簡單的例子來了解如何建立一個數據庫、一個表格以及如何從資料庫中插入和檢索資料。我們將新增姓名和年齡,然後我們將從表格中檢索相同的資料。以下是新增不同控制元件的 XAML 程式碼。

<Page 
   x:Class = "UWPSQLiteDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPSQLiteDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}" >
      <Button x:Name = "Retrieve" Content = "Retrieve" HorizontalAlignment = "Left"  
         VerticalAlignment = "Top" Margin = "384,406,0,0"  
         Click = "Retrieve_Click"/>
			
      <Button x:Name = "Add" Content = "Add" HorizontalAlignment = "Left"  
         VerticalAlignment = "Top" Margin = "291,406,0,0" Click = "Add_Click"/>
			
      <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"  
         TextWrapping = "Wrap" Text = "Name" VerticalAlignment = "Top"  
         Margin = "233,280,0,0" Width = "52"/>
			
      <TextBox x:Name = "textBox" HorizontalAlignment = "Left" TextWrapping = "Wrap"  
         VerticalAlignment = "Top" Margin = "289,274,0,0" Width = "370"/>
			
      <TextBlock x:Name = "textBlock1" HorizontalAlignment = "Left"  
         TextWrapping = "Wrap" Text = "Age" VerticalAlignment = "Top"  
         Margin = "233,342,0,0" Width = "52"/>
			
      <TextBox x:Name = "textBox1" HorizontalAlignment = "Left" TextWrapping = "Wrap"  
         VerticalAlignment = "Top" Margin = "289,336,0,0" Width = "191"/>
			
      <TextBlock x:Name = "textBlock2" HorizontalAlignment = "Left"  
         Margin = "290,468,0,0" TextWrapping = "Wrap"  
         VerticalAlignment = "Top" Width = "324" Height = "131"/>
			
   </Grid>
	
</Page>		   

以下是事件和SQLite 資料庫的 C# 實現。

using SQLite.Net.Attributes; 

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 

using Windows.Foundation; 
using Windows.Foundation.Collections; 

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation;  

// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 
 
namespace UWPSQLiteDemo {
 
   /// <summary>
      /// An empty page that can be used on its own or navigated to within a Frame.
   /// </summary>
	
   public sealed partial class MainPage : Page {
      string path; 
      SQLite.Net.SQLiteConnection conn; 
		
      public MainPage(){
         this.InitializeComponent();  
         path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,
            "db.sqlite"); 
         conn = new SQLite.Net.SQLiteConnection(new 
            SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);  
         conn.CreateTable<Customer>(); 
      }
		
      private void Retrieve_Click(object sender, RoutedEventArgs e) { 
         var query = conn.Table<Customer>(); 
         string id = ""; 
         string name = ""; 
         string age = "";  
			
         foreach (var message in query) {
            id = id + " " + message.Id; 
            name = name + " " + message.Name; 
            age = age + " " + message.Age; 
         }
			
         textBlock2.Text = "ID: " + id + "\nName: " + name + "\nAge: " + age; 
      }  
		
      private void Add_Click(object sender, RoutedEventArgs e){ 
       
         var s = conn.Insert(new Customer(){
            Name = textBox.Text, 
            Age = textBox1.Text 
         }); 
			
      } 
   } 
	
   public class Customer {
      [PrimaryKey, AutoIncrement] 
      public int Id { get; set; } 
      public string Name { get; set; } 
      public string Age { get; set; } 
   } 
	
} 

編譯並執行上述程式碼後,您將看到以下視窗。

UWP SQLite Execute

輸入姓名年齡,然後點選新增按鈕。

UWP SQLite Add button

現在點選檢索按鈕。您將在文字塊上看到以下資料。

UWP SQLite Retrieve

ID 欄位是主鍵和自動增量欄位,在 Customer 類中指定。

[PrimaryKey, AutoIncrement] 
public int Id { get; set; }

Windows10 開發 - 應用通訊

應用間通訊意味著您的應用程式可以與安裝在同一裝置上的其他應用程式進行通訊。這並不是通用 Windows 平臺 (UWP) 應用程式的新功能,在 Windows 8.1 中也可用。

在 Windows 10 中,引入了一些新的改進方法來輕鬆地在同一裝置上的應用程式之間進行通訊。兩個應用程式之間的通訊可以透過以下方式實現:

  • 一個應用程式啟動另一個應用程式並傳遞一些資料。
  • 應用程式之間簡單地交換資料,無需啟動任何內容。

應用間通訊的主要優勢在於,您可以將應用程式分解成更小的塊,這些塊可以更容易地維護、更新和使用。

準備您的應用

如果您按照以下步驟操作,其他應用程式就可以啟動您的應用程式。

  • 在應用程式包清單中新增協議宣告。

  • 雙擊Package.appxmanifest檔案,該檔案位於解決方案資源管理器中,如下所示。

  • 轉到宣告選項卡,並寫入協議名稱,如下所示。

Getting App Ready
  • 下一步是新增啟用程式碼,以便應用程式在被其他應用程式啟動時能夠做出相應的響應。

  • 要響應協議啟用,我們需要重寫啟用類的OnActivated方法。因此,在App.xaml.cs檔案中新增以下程式碼。

protected override void OnActivated(IActivatedEventArgs args) {
 
   ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;
	
   if (args != null){ 

      Frame rootFrame = Window.Current.Content as Frame;
	  
      // Do not repeat app initialization when the Window already has content, 
      // just ensure that the window is active
	  
      if (rootFrame == null){ 
		 
         // Create a Frame to act as the navigation context and navigate to the first page
         rootFrame = new Frame(); 
		 
         // Set the default language 
         rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];  
         rootFrame.NavigationFailed += OnNavigationFailed;
		 
         // Place the frame in the current Window 
         Window.Current.Content = rootFrame; 
      } 
		
      if (rootFrame.Content == null){
	  
         // When the navigation stack isn't restored, navigate to the  
         // first page, configuring the new page by passing required  
         // information as a navigation parameter 
		 
         rootFrame.Navigate(typeof(MainPage), null); 
      } 
		
      // Ensure the current window is active 
      Window.Current.Activate(); 
		
   } 
} 
  • 要啟動應用程式,您可以簡單地使用Launcher.LaunchUriAsync方法,該方法將使用此方法中指定的協議啟動應用程式。

await Windows.System.Launcher.LaunchUriAsync(new Uri("win10demo:?SomeData=123"));

讓我們透過一個簡單的示例來了解這一點,在這個示例中,我們有兩個 UWP 應用程式,分別是ProtocolHandlerDemoFirstProtocolHandler

在此示例中,ProtocolHandlerDemo應用程式包含一個按鈕,點選該按鈕將開啟FirstProtocolHandler應用程式。

以下是 ProtocolHandlerDemo 應用程式的 XAML 程式碼,其中包含一個按鈕。

<Page 
   x:Class = "ProtocolHandlerDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:ProtocolHandlerDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <Button x:Name = "LaunchButton" Content = " Launch First Protocol App"
         FontSize = "24" HorizontalAlignment = "Center" 
         Click = "LaunchButton_Click"/> 
   </Grid> 
	
</Page>

以下是 C# 程式碼,其中實現了按鈕點選事件。

using System; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;  

// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace ProtocolHandlerDemo {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
   
   public sealed partial class MainPage : Page {
   
      public MainPage(){ 
         this.InitializeComponent(); 
      }
		
      private async void LaunchButton_Click(object sender, RoutedEventArgs e) {
         await Windows.System.Launcher.LaunchUriAsync(new 
            Uri("win10demo:?SomeData=123")); 
      }
		
   }
}

現在讓我們看看FirstProtocolHandler應用程式表格。以下是建立具有某些屬性的文字塊的 XAML 程式碼。

<Page 
   x:Class = "FirstProtocolHandler.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:FirstProtocolHandler" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <TextBlock Text = "You have successfully launch First Protocol Application" 
         TextWrapping = "Wrap" Style = "{StaticResource SubtitleTextBlockStyle}"  
         Margin = "30,39,0,0" VerticalAlignment = "Top" HorizontalAlignment = "Left" 
         Height = "100" Width = "325"/> 
   </Grid> 
	
</Page>

以下是App.xaml.cs檔案的 C# 實現,其中重寫了OnActicated。在App.xaml.cs檔案中的 App 類中新增以下程式碼。

protected override void OnActivated(IActivatedEventArgs args) { 
   ProtocolActivatedEventArgs protocolArgs = args as ProtocolActivatedEventArgs;
	
   if (args != null) {
      Frame rootFrame = Window.Current.Content as Frame;  
		
      // Do not repeat app initialization when the Window already has content, 
      // just ensure that the window is active 
		
      if (rootFrame == null) {

         // Create a Frame to act as the navigation context and navigate to 
            the first page 
         rootFrame = new Frame(); 
		 
         // Set the default language 
         rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];  
         rootFrame.NavigationFailed += OnNavigationFailed; 
		 
         // Place the frame in the current Window 
         Window.Current.Content = rootFrame; 
      }  
		
      if (rootFrame.Content == null) {
		
         // When the navigation stack isn't restored navigate to the 
         // first page, configuring the new page by passing required 
         // information as a navigation parameter 
		 
         rootFrame.Navigate(typeof(MainPage), null); 
      }
		
      // Ensure the current window is active 
      Window.Current.Activate(); 
   } 
} 

當您在模擬器上編譯並執行ProtocolHandlerDemo應用程式時,您將看到以下視窗。

Getting App Ready Execute

現在,當您點選按鈕時,它將開啟FirstProtocolHandler應用程式,如下所示。

Getting App Ready With Button

Windows 10 開發 - 本地化

Windows 在全球範圍內使用,在各種不同的市場和針對不同文化、地區或語言的目標受眾。本地化是指將應用程式資源翻譯成特定文化支援的本地化版本。

當您僅用一種語言開發任何應用程式時,這意味著您只是限制了自己的業務和客戶。如果您想擴大客戶群,從而增加您的業務,那麼您的應用程式必須在全球範圍內可用並可訪問。對您的產品進行經濟高效的本地化是接觸更多客戶的最佳和最經濟的方式之一。

在 Windows 10 中,使用resx檔案建立可本地化的應用程式非常容易,這是本地化最簡單的解決方案。

讓我們透過遵循下面提到的所有步驟,透過一個簡單的例子來理解這一點。

翻譯 UI 資源

您可以將 UI 的字串資源放入資源 (resw) 檔案中,而不是直接將它們放在程式碼或標記中,然後您可以從程式碼或標記中引用這些字串。請按照以下步驟將字串新增到資原始檔。

  • 建立一個新的通用 Windows 平臺 (UWP) 應用程式。

  • 解決方案資源管理器中,右鍵單擊專案並選擇新增 > 新建資料夾

App Localization
  • 將新資料夾的名稱更改為“Strings”

  • 右鍵單擊Strings資料夾,並新增一個名為“en-US”的新資料夾。這些是特定於語言和國家/地區名稱的命名約定,可以在國家/地區語言支援 (NLS) API 參考 msdn.microsoft.com頁面上找到。

  • 右鍵單擊en-US資料夾,然後選擇新增 > 新建項…。

App Localization
  • 將開啟以下對話方塊。
App Localization
  • 選擇“資原始檔 (.resw)”,然後單擊新增按鈕。

  • 現在讓我們轉到 XAML 檔案,並新增一個具有某些屬性的 Hub 控制元件,如下所示。

<Page 
   x:Class = "UWPLocalizationDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPLocalizationDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <Hub x:Name = "textBlock" x:Uid = "HubControl" Background = "Black" 
         Foreground = "White" Header = "Localization Demo"/>
   </Grid> 
	
</Page>
  • x:Uid = “HubControl”是用於本地化的識別符號。

  • 現在,當編譯並執行上述程式碼時,您將看到以下視窗。

與 Hub 相關的所有資訊,例如標題、前景色和背景顏色,都設定在 XAML 中。

App Localization
  • 現在在Strings/en-US資料夾中的Resource.resw檔案中新增一些資訊,如下所示。

App Localization Add Name
  • 您需要將每個需要本地化文字的控制元件與 .resw檔案關聯。您可以透過在 XAML 元素上使用x:Uid屬性來實現,如下所示:

    • x:Uid = “HubControl”用於在resw檔案中為標題、前景色和背景顏色分配字串。

  • 現在,當您在模擬器上編譯並執行應用程式時,您將看到以下視窗。您可以看到標題、前景色和背景顏色的值是從Resources.resw檔案中獲取的。

App Localization
  • 您可以為其他語言(例如法語、德語和日語等)手動新增其他Resource.resw檔案,就像我們為英語-美國所做的那樣,但 Microsoft 還提供了多語言應用程式工具包,藉助該工具包,您可以輕鬆地將Resource.resw翻譯成其他語言。

  • 轉到工具 > 擴充套件和更新選單,並搜尋多語言應用程式工具包。

Multilingual app
  • 下載並安裝此工具包。安裝完成後,重新啟動 Visual Studio 並開啟同一個專案。

  • 現在從工具 > 多語言應用程式工具包選單選項中啟用此工具包。

Multilingual app
  • 現在您可以為其他語言新增翻譯。

  • 右鍵單擊解決方案資源管理器中的專案,然後從選單中選擇多語言應用程式工具包 > 新增翻譯語言選項。

Multilingual App Toolkit
  • 將開啟以下翻譯語言對話方塊。您可以選擇任何您想要的語言,以針對這些文化本地化您的應用程式。

Localization Translation Languages
  • 讓我們選擇德語,然後單擊確定按鈕。

Localization German Language
  • 您還可以看到Resources.resw檔案是在Strings\de資料夾內建立的。

  • 現在,您將看到另一個MultiLingualResources已新增到*.xlf檔案中。雙擊此檔案,這將開啟多語言編輯器以檢查和驗證已翻譯的字串,並在需要時進行一些更改。

Localization Multilingual Editor
  • 進行更改並驗證背景顏色是否已更改為棕色,以及標題文字是否已正確翻譯成德語。

  • 如上例所示,Hub 的背景顏色已從藍色更改為棕色,前景色保持不變。

  • 現在開啟Resources.resw,它位於Strings\de資料夾內。

App Localization Strings
  • 您可以看到這裡只提到了兩個字串,因為我們沒有在多語言編輯器中更改前景色。

要檢查應用程式的本地化版本,請更改計算機的區域性。要更改計算機的區域性,請按照以下步驟操作。

  • 讓我們轉到 PC 設定並選擇時間和語言。
Localization Time Setting
  • 在左側窗格中,選擇區域和語言,然後單擊新增語言

Localization Regions and Language
  • 選擇德語 (德國)語言,如上所示,這將開啟另一個對話方塊。

Localization Deutsch German
  • 現在選擇德語 (德國)並關閉此對話方塊。

Localization Germany
  • 將德語設定為預設語言。
  • 現在執行您的應用程式,它將顯示以下視窗。
Localization Execution
  • 現在您可以看到您的應用程式的德語輸出。

Windows 10 開發 - 生命週期

從歷史上看,Windows 擁有一個環境,使用者可以在其中同時執行多個應用程式。使用者可以輕鬆地在不同的應用程式之間切換。此模型不適用於手機或平板電腦裝置,因為這些裝置通常以單一應用程式為中心。

Windows 8 應用商店應用程式程式設計師面臨的最重大挑戰之一是管理和理解應用程式的生命週期。如果您一直在構建 Windows Phone 應用程式,那麼其中許多內容將是熟悉的。

  • 在 Windows 8 下,作業系統管理應用程式的生命週期,雖然使用者可以終止應用程式,但通常使用者會開啟新的應用程式,而不會有意識地終止正在執行的應用程式。

  • Windows 10 的通用 Windows 平臺 (UWP) 解決了這些問題,為桌面使用者提供了一些很酷的功能,以便多個應用程式可以以多視窗體驗執行。

Windows 應用程式可以在基本級別存在三種狀態,如下所示。

  • 執行中

  • 掛起

  • 終止

App Lifecycle
  • 當用戶啟動/啟用任何應用程式時,它將進入執行中狀態。

  • 如果使用者不使用應用程式並且它不再處於前臺,則可以將其掛起。

  • 從掛起狀態,應用程式可以恢復該應用程式或終止作業系統以回收系統資源。

程序狀態轉換

瞭解正在執行的應用程式中的程序狀態轉換非常重要。當用戶首次啟動應用程式時,將顯示啟動螢幕,然後應用程式開始執行。

Process State Transition

該過程可以解釋如下:

  • 當應用程式掛起時,您的應用程式有 5 秒鐘的時間來處理該掛起事件。

  • 當應用程式掛起時,絕對不會執行任何程式碼,也不會分配任何資源。

  • 恢復時,將通知應用程式它已恢復。如果您來自掛起狀態,則無需執行任何操作。

  • 在記憶體壓力下,您的應用程式可能會被終止。

  • 請記住,在那個時候您不會收到通知,因此,您需要在進入掛起應用程式狀態時執行任何儲存操作。

當應用程式在執行掛起狀態之間來回轉換時,分別觸發掛起和恢復事件。

有時,您需要儲存資料。然後,您必須呼叫如下所示的非同步方法。

Application.Current.Suspending += new SuspendingEventHandler(App_Suspending); 

async void App_Suspending(Object sender, Windows.ApplicationModel.SuspendingEventArgs e){ 
   // Create a simple setting  
   localSettings.Values["FirstName"] = fName.Text; 
   localSettings.Values["LastName"] = lName.Text; 
   localSettings.Values["Email"] = email.Text; 
}

Application.Current.Resuming += new EventHandler<Object>(App_Resuming); 

private void App_Resuming(Object sender, Object e){ 
   fName.Text = localSettings.Values["FirstName"]; 
   lName.Text = localSettings.Values["LastName"]; 
   email.Text = localSettings.Values["Email"]; 
}

讓我們研究一個示例,其中控制元件如以下給定的 XAML 檔案中所示新增。

<Page 
   x:Class = "UWPLifeCycleDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPLifeCycleDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
    
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <Hub Header = "Details" />
		
      <StackPanel VerticalAlignment = "Top" HorizontalAlignment = "Left" 
         Margin = "12,64,0,0">
			
         <TextBox Header = "First Name" Text = "{Binding FirstName, 
            Mode = TwoWay, UpdateSourceTrigger = PropertyChanged}" 
            Width = "200" />
				
         <TextBox Header = "Last Name" Text = "{Binding LastName, Mode = TwoWay, 
            UpdateSourceTrigger = PropertyChanged}" Width = "200" />
				
         <TextBox Header = "Email" Text = "{Binding Email, Mode = TwoWay, 
            UpdateSourceTrigger = PropertyChanged}" Width = "200" />
				
         <Button Margin = "0,12">Submit</Button>
			
      </StackPanel>
		
   </Grid>
	
</Page>

下面是 C# 程式碼,其中實現了掛起和恢復事件。當前資料將儲存在掛起事件中的本地設定中,然後從本地設定中的恢復事件中檢索資料,如下所示。

using System; 
using System.ComponentModel; 
using System.Runtime.CompilerServices; 

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
 
namespace UWPLifeCycleDemo {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page{
      var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; 
		
      public MainPage() {
         this.InitializeComponent(); 
         Application.Current.Suspending += new SuspendingEventHandler(App_Suspending); 
         Application.Current.Resuming += new EventHandler<Object>(App_Resuming); 
      } 
		
      async void App_Suspending(Object sender, Windows.ApplicationModel.SuspendingEventArgs e){
         
         // Create a simple setting 
         localSettings.Values["FirstName"] = fName.Text; 
         localSettings.Values["LastName"] = lName.Text; 
         localSettings.Values["Email"] = email.Text; 
      } 
		
      private void App_Resuming(Object sender, Object e){
         fName.Text = localSettings.Values["FirstName"]; 
         lName.Text = localSettings.Values["LastName"]; 
         email.Text = localSettings.Values["Email"]; 
      }
		
   } 
	
   public abstract class BindableBase : INotifyPropertyChanged {
      private string _FirstName = default(string);
		
      public string FirstName { 
         get { return _FirstName; } 
         set { Set(ref _FirstName, value); } 
      } 
		
      private string _LastName = default(string);
		
      public string LastName { 
         get { return _LastName; } 
         set { Set(ref _LastName, value); } 
      } 
		
      private string _Email = default(string);
		
      public string Email { 
         get { return _Email; } 
         set { Set(ref _Email, value); } 
      } 
		
      public event PropertyChangedEventHandler PropertyChanged;
		
      public void RaisePropertyChanged([CallerMemberName]string propertyName = null) {
         PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); 
      } 
		
      public void Set<T>(ref T storage, T value, 
         [CallerMemberName()]string propertyName = null){ 

         if (!object.Equals(storage, value)){
            storage = value; 
            RaisePropertyChanged(propertyName); 
         } 
      } 
   } 
}

編譯並執行上述程式碼後,您將看到以下視窗。現在編寫所需的資訊。

Compile Execution

讓我們轉到生命週期事件下拉選單並選擇掛起。現在您的應用程式將被掛起,所需的資訊將儲存在本地設定中。請參見下面給出的螢幕截圖。

Lifecycle Events

現在,當您要恢復應用程式時,從生命週期事件選單中選擇恢復選項。

Lifecycle Events Menu

現在您將看到從本地設定中檢索儲存的資訊,並且應用程式從掛起狀態恢復到相同的狀態。

Lifecycle Retrive

Windows 10 開發 - 後臺執行

通用 Windows 平臺 (UWP) 引入了新的機制,允許應用程式在應用程式沒有在前臺執行時執行某些功能。UWP 還增強了應用程式在後臺擴充套件執行時間的能力,用於後臺任務和觸發器。後臺執行是應用程式生命週期的真正補充。

後臺任務的重要功能如下:

  • 後臺任務由系統或時間事件觸發,並且可以受一個或多個條件約束。

  • 當觸發後臺任務時,其關聯的處理程式執行並執行後臺任務的工作。

  • 即使註冊了後臺任務的應用已掛起,後臺任務也可以執行。

  • 它們是標準應用程式平臺的一部分,本質上為應用程式提供了註冊系統事件(觸發器)的能力。當該事件發生時,它們在後臺執行預定義的程式碼塊。系統觸發器包括網路連線更改或系統時區等事件。

  • 後臺執行沒有保證,因此不適用於關鍵功能。

  • 作業系統對同時執行的後臺任務數量有限制。因此,即使觸發器被觸發且條件滿足,任務仍然可能無法執行。

建立和註冊後臺任務

建立一個後臺任務類並將其註冊為在您的應用不在前臺時執行。您可以透過編寫實現IBackgroundTask介面的類來在後臺執行程式碼。以下示例程式碼顯示了後臺任務類的非常基本的起點。

public sealed class MyBackgroundTask : IBackgroundTask { 
   public void Run(IBackgroundTaskInstance taskInstance){ 
      // write code 
   } 
}

您可以按如下方式請求訪問後臺任務。

var access = await BackgroundExecutionManager.RequestAccessAsync();
 
switch (access) {
 
   case BackgroundAccessStatus.Unspecified: 
      break; 
   case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity: 
      break; 
   case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity: 
      break; 
   case BackgroundAccessStatus.Denied: 
      break; 
   default: 
      break; 
}

要構建和註冊後臺任務,請使用以下程式碼。

var task = new BackgroundTaskBuilder {
   Name = "My Task", 
   TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString() 
}; 

var trigger = new ApplicationTrigger(); 
task.SetTrigger(trigger);  
task.Register(); 
 
await trigger.RequestAsync();

讓我們透過遵循以下所有步驟來了解後臺任務的一個簡單示例。

  • 建立一個新的空白 UWP 專案‘UWPBackgroundDemo’並在 XAML 檔案中新增一個按鈕。

<Page 
   x:Class = "UWPBackgroundDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPBackgroundDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <Button x:Name = "button" Content = "Button" 
         HorizontalAlignment = "Left" Margin = "159,288,0,0" 
         VerticalAlignment = "Top" Click = "button_Click"/> 
   </Grid>
	
</Page>
  • 下面是在其中註冊後臺任務的按鈕點選事件實現。

using System; 

using Windows.ApplicationModel.Background; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
 
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace UWPBackgroundDemo {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary>
	
   public sealed partial class MainPage : Page {

      public MainPage() {
         this.InitializeComponent(); 
      }  
		
      private async void button_Click(object sender, RoutedEventArgs e) {
         var access = await BackgroundExecutionManager.RequestAccessAsync(); 
		 
         switch (access){ 
            case BackgroundAccessStatus.Unspecified: 
               break; 
            case BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity: 
               break; 
            case BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity: 
               break; 
            case BackgroundAccessStatus.Denied: 
               break; 
            default: 
               break; 
         } 
			
         var task = new BackgroundTaskBuilder {  
            Name = "My Task", 
            TaskEntryPoint = typeof(BackgroundStuff.MyBackgroundTask).ToString() 
         }; 
			
         var trigger = new ApplicationTrigger(); 
         task.SetTrigger(trigger);  
			
         var condition = new SystemCondition(SystemConditionType.InternetAvailable);  
         task.Register(); 
			
         await trigger.RequestAsync(); 
      } 
   } 
} 
  • 現在建立另一個專案,但這次從選單中選擇 Windows 執行時元件(通用 Windows),併為該專案命名為Background stuff

Background stuff
  • 下面是 C# 程式碼,其中包含MyBackgroundTask類實現,它將執行後臺任務。

using Windows.ApplicationModel.Background; 
using Windows.UI.Notifications; 
 
namespace BackgroundStuff { 
   public sealed class MyBackgroundTask : IBackgroundTask { 
	
      public void Run(IBackgroundTaskInstance taskInstance) {
         SendToast("Hi this is background Task"); 
      } 
		
      public static void SendToast(string message) { 
         var template = ToastTemplateType.ToastText01; 
         var xml = ToastNotificationManager.GetTemplateContent(template); 
         var elements = xml.GetElementsByTagName("Test"); 
         var text = xml.CreateTextNode(message); 
			
         elements[0].AppendChild(text); 
         var toast = new ToastNotification(xml); 
         ToastNotificationManager.CreateToastNotifier().Show(toast); 
      } 
   } 
}
  • 為了使此專案在UWPBackgroundDemo專案中可訪問,請在解決方案資源管理器中右鍵單擊引用>新增引用,然後新增BackgroundStuff專案。

Background stuff Sec
  • 現在,讓我們轉到UWPBackgroundDemo專案的Package.appxmanifest檔案,並在“宣告”選項卡中新增以下資訊。

Background stuff
  • 首先構建 Background stuff 專案,然後構建並執行UWPBackgroundDemo專案。

  • 編譯並執行上述程式碼後,您將看到以下視窗。

Background stuff
  • 當您單擊按鈕時,它將執行後臺任務,並在視窗的右側顯示通知。

Windows 10 開發 - 服務

在本章中,我們將學習 UWP 應用如何幫助或為另一個通用 Windows 平臺 (UWP) 應用程式提供服務。實際上,本章是後臺執行章節的擴充套件,也是其一個特例。

  • 在 Windows 10 中,應用服務是應用為其他應用提供服務的一種方式或機制。

  • 應用服務以後臺任務的形式工作。

  • 前臺應用可以呼叫另一個應用中的應用服務以在後臺執行任務。

APP Services

應用服務類似於 Web 服務,但應用服務用於 Windows 10 裝置上。

通用 Windows 平臺 (UWP) 應用程式可以透過多種方式與另一個 UWP 應用程式互動:

  • 使用 LaunchUriAsync 的 URI 關聯
  • 使用 LaunchFileAsync 的檔案關聯
  • 使用 LaunchUriForResultsAsync 啟動結果
  • 應用服務

前三種方式用於兩個應用程式都在前臺的情況下,但應用服務用於後臺任務,在這種情況下,客戶端應用程式必須在前臺並可用於使用應用服務。

應用服務在提供非視覺化服務的應用程式中非常有用,例如條形碼掃描器,其中前臺應用程式將獲取影像並將這些位元組傳送到應用服務以識別條形碼。

為了理解所有這些概念,讓我們在 Microsoft Visual Studio 2015 中建立一個名為AppServiceProvider的新 UWP 專案。

現在在Package.appmenifest檔案中,新增以下資訊。

APP Services

要建立一個可以由前臺應用程式呼叫的應用服務,讓我們向解決方案新增一個新的Windows 執行時元件專案,命名為MyAppService,因為應用服務作為後臺任務實現。

AppServiceProvider專案中新增對MyAppService專案的引用。

現在從MyAppService專案中刪除class1.cs檔案,並新增一個具有清單名稱的新類,該類將實現IBackgrounTask介面。

IBackgrounTask介面只有一個方法“Run”,需要為後臺任務實現。

public sealed class Inventory : IBackgroundTask { 
   public void Run(IBackgroundTaskInstance taskInstance) { 
      
   } 
}

建立後臺任務時,將呼叫Run() 方法,當 Run 方法完成時,後臺任務將終止。為了保持後臺任務以服務請求,程式碼獲取延遲。

應用服務程式碼位於OnRequestedReceived()中。在此示例中,庫存專案的索引傳遞到服務,以檢索指定庫存專案的名稱和價格。

private async void OnRequestReceived(AppServiceConnection sender, 
   AppServiceRequestReceivedEventArgs args) {
      // Get a deferral because we use an awaitable API below to respond to the message 
}

下面是 C# 中 Inventory 類的完整實現。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

using Windows.ApplicationModel.AppService; 
using Windows.ApplicationModel.Background; 
using Windows.Foundation.Collections;  

namespace MyAppService{
   public sealed class Inventory : IBackgroundTask { 
	
      private BackgroundTaskDeferral backgroundTaskDeferral; 
      private AppServiceConnection appServiceconnection; 
		
      private String[] inventoryItems = new string[] { "Robot vacuum", "Chair" }; 
      private double[] inventoryPrices = new double[] { 129.99, 88.99 };
		
      public void Run(IBackgroundTaskInstance taskInstance) {
         this.backgroundTaskDeferral = taskInstance.GetDeferral(); 
         taskInstance.Canceled += OnTaskCanceled;  
         var details = taskInstance.TriggerDetails as AppServiceTriggerDetails;
			
         appServiceconnection = details.AppServiceConnection;
         appServiceconnection.RequestReceived += OnRequestReceived; 
      } 
		
      private async void OnRequestReceived(AppServiceConnection sender,
         AppServiceRequestReceivedEventArgs args) {
        
            var messageDeferral = args.GetDeferral(); 
            ValueSet message = args.Request.Message; 
            ValueSet returnData = new ValueSet();  
				
            string command = message["Command"] as string; 
            int? inventoryIndex = message["ID"] as int?;  
            if (inventoryIndex.HasValue && 
				
            inventoryIndex.Value >= 0 && 
            inventoryIndex.Value < inventoryItems.GetLength(0)) {
		 
               switch (command) {
			
                  case "Price": {
                     returnData.Add("Result", inventoryPrices[inventoryIndex.Value]); 
                     returnData.Add("Status", "OK"); 
                     break; 
                  } 
					
                  case "Item": {
                     returnData.Add("Result", inventoryItems[inventoryIndex.Value]); 
                     returnData.Add("Status", "OK"); 
                     break; 
                  }  
					
                  default: {
                     returnData.Add("Status", "Fail: unknown command"); 
                     break; 
                  }
               } else {
                  returnData.Add("Status", "Fail: Index out of range"); 
               } 
            }			
            await args.Request.SendResponseAsync(returnData); 
            messageDeferral.Complete(); 
      } 
		
      private void OnTaskCanceled(IBackgroundTaskInstance sender,
         BackgroundTaskCancellationReason reason){ 
            if (this.backgroundTaskDeferral != null) {
               // Complete the service deferral. 
               this.backgroundTaskDeferral.Complete(); 
            } 
      } 
   } 
}

讓我們建立一個客戶端應用,方法是在 XAML 檔案中新增一個新的空白 UWP 專案ClientApp並新增一個按鈕、一個文字框和兩個文字塊,如下所示。

<Page 
   x:Class = "ClientApp.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:ClientApp" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <TextBlock HorizontalAlignment = "Left" Text = "Enter Item No." 
         Margin = "52,40,0,0" TextWrapping = "Wrap"
         VerticalAlignment = "Top" Height = "32" Width = "268"/> 
			
      <Button x:Name = "button" Content = "Get Info" HorizontalAlignment = "Left"  
         Margin = "255,96,0,0" VerticalAlignment = "Top" Click = "button_Click"/>
			
      <TextBox x:Name = "textBox" HorizontalAlignment = "Left" Margin = "52,96,0,0"  
         TextWrapping = "Wrap" VerticalAlignment = "Top" Width = "168"/>
			
      <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"  
         Margin = "52,190,0,0" TextWrapping = "Wrap"  
         VerticalAlignment = "Top" Height = "32" Width = "268"/> 
   </Grid> 
	
</Page>

下面是在其中請求應用服務的按鈕點選事件實現。

using System; 

using Windows.ApplicationModel.AppService; 
using Windows.Foundation.Collections;
 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;
  
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace ClientApp {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
   
      private AppServiceConnection inventoryService; 
	  
      public MainPage() {
         this.InitializeComponent(); 
      } 
		
      private async void button_Click(object sender, RoutedEventArgs e){
	  
         // Add the connection. 
         if (this.inventoryService == null) {
		 
            this.inventoryService = new AppServiceConnection(); 
            this.inventoryService.AppServiceName = "com.microsoft.inventory"; 
            this.inventoryService.PackageFamilyName = 
               "bb1a8478-8005-46869923-e525ceaa26fc_4sz2ag3dcq60a"; 
					
            var status = await this.inventoryService.OpenAsync();
				
            if (status != AppServiceConnectionStatus.Success) {
               button.Content = "Failed to connect"; 
               return; 
            } 
         } 
			
         // Call the service. 
         int idx = int.Parse(textBox.Text); 
         var message = new ValueSet(); 
			
         message.Add("Command", "Item"); 
         message.Add("ID", idx); 
			
         AppServiceResponse response = await 
            this.inventoryService.SendMessageAsync(message); 
         string result = ""; 
			
         if (response.Status == AppServiceResponseStatus.Success) { 
            // Get the data  that the service sent  to us. 
            if (response.Message["Status"] as string == "OK") {
               result = response.Message["Result"] as string; 
            } 
         } 
			
         message.Clear(); 
         message.Add("Command", "Price"); 
         message.Add("ID", idx); 
			
         response = await this.inventoryService.SendMessageAsync(message);
			
         if (response.Status == AppServiceResponseStatus.Success){
            // Get the data that the service sent to us. 
            if (response.Message["Status"] as string == "OK") {
               result += " : Price = " + "$"+ response.Message["Result"] as string; 
            } 
         }
			
         textBlock.Text = result;  
      } 
   } 
}

要執行此應用程式,您需要將ClientApp專案設定為解決方案資源管理器中的啟動專案,然後從生成>部署解決方案中部署此解決方案。

APP Services

編譯並執行上述程式碼後,您將看到以下視窗。在應用服務中,我們只添加了兩個專案的資料。因此,您可以輸入 0 或 1 以獲取這些專案的資料。

APP Services

當您輸入 0 並單擊按鈕時,它將執行應用服務作為後臺任務,並在文字塊上顯示專案資訊。

Windows 10 開發 - Web 平臺

在 Windows 10 中,開發人員可以非常輕鬆地建立通用 Windows 平臺 (UWP) 應用程式,並在該應用程式上託管其網站,然後將其釋出到 Windows 應用商店以供下載。

優勢

  • 藉助 Windows 10 中的此新功能,Web 開發人員可以輕鬆地將其網站的元件轉換為 Windows 應用。

  • 但是,所有這些元件仍將遠端託管在其自己的 Web 伺服器上。

  • 此外,他們還可以訪問通用 API,這將允許開發人員訪問一些很酷的東西,例如通知、相機、日曆、Cortana 等。

微軟希望此功能和能力能夠吸引更多開發人員為 Windows 10 平臺編寫應用,其中包括:

  • 桌面
  • 智慧手機
  • Xbox
  • 平板電腦
  • HoloLens 及其他裝置

目前,此功能只有一個問題,那就是安全性。顯然,微軟需要儘快解決這個問題。

讓我們透過一個示例來了解,在這個示例中,我們將託管一個網站並將其轉換為 Windows 應用。

請按照以下步驟操作。

  • 檔案>新建>專案建立一個新的通用 Windows 專案。

Web Platform Project
  • 從“新建專案”對話方塊的左側窗格中選擇JavaScript>Windows>通用選項。

  • 從中間窗格中選擇空白應用(通用 Windows)

  • 在名稱欄位中輸入UWPWebApp,然後單擊確定按鈕。

  • 如果您檢視解決方案資源管理器視窗,您將看到一些檔案和資料夾。

Web Platform File
  • 刪除css、js、WinJS資料夾和default.html檔案,因為在此示例中,我們只是託管一個網站,並且我們假設所有內容都在遠端伺服器上。因此,我們不需要大多數本地檔案。

  • 刪除上述檔案和資料夾後,現在雙擊package.appxmanifest檔案,您將看到以下視窗。

Web Platform After Delete
  • 現在透過用 URL 替換“啟動頁”欄位中的default.html來指定網站 URL。為了演示目的,我們將使用 URLhttps://www.google.com.pk/網站。

Web Platform URL Replace
  • 現在轉到內容 URI選項卡,併為您的 Web 應用定義規則和訪問許可權。

Web Platform Count URLs
  • 在 URI 欄位中,指定您的網站連結,然後從規則下拉列表中選擇包含,從WinRT 訪問中選擇全部

  • 執行此應用程式時,您將在應用程式上看到 Google 啟動頁面,如下所示。

Google Start Page

Windows 10 開發 - 連線體驗

正如我們已經知道的,在 Windows 10 中,我們可以建立一個可以在多個 Windows 10 裝置上執行和執行的應用程式。假設我們有這些不同的裝置,並且我們希望讓它感覺就像它是一個應用程式,即使它在不同的裝置上執行。

在通用 Windows 平臺 (UWP) 中,您可以在所有 Windows 10 裝置上執行單個應用程式,並且可以給使用者一種它是一個應用程式的感覺。這被稱為**連線體驗**。

連線體驗的重要特性 -

  • Windows 10 是邁向更個性化計算時代的第一步,在這個時代,您的應用程式、服務和內容可以跨裝置無縫且輕鬆地移動。

  • 透過連線體驗,您可以輕鬆共享與該應用程式相關的資料和個人設定,並且這些資料和設定將在所有裝置上可用。

在本章中,我們將學習 -

  • 這些共享資料或設定將儲存在何處,以便該應用程式可以在您的裝置上使用。

  • 如何識別使用者;即,它是同一個使用者在不同的裝置上使用同一個應用程式。

Windows 10 邁出了大膽的一步。當您使用 Microsoft 帳戶 (MSA) 或企業帳戶(工作帳戶)登入 Windows 10 時,假設 -

  • 對於 MSA 帳戶,您可以免費訪問 OneDrive,對於企業帳戶,您可以訪問 Active Directory (AD) 和 Azure Active Directory (AAD)(其是雲版本)。

  • 您可以訪問不同的應用程式和資源。

  • 裝置和應用程式處於漫遊狀態和設定中。

Windows 10 Devices

Windows 10 中的漫遊

當您登入到 PC 時,您可以設定一些首選項,例如鎖定螢幕或背景顏色,或個性化您的各種設定。如果您有多臺計算機或裝置執行 Windows 10,則當您使用同一帳戶登入其他裝置時,您在一臺裝置上的首選項和設定將從雲端同步。

在 Windows 10 中,當您設定或個性化應用程式設定時,這些設定將與 UWP 中提供的漫遊 API 一起漫遊。當您在其他裝置上再次運行同一應用程式時,它將首先檢索設定並將這些設定應用於該裝置上的應用程式。

Personalized Settings

將漫遊資料上傳到雲端的大小限制為 100KB。如果超出此限制,則同步將停止,並且只會像本地資料夾一樣執行。

**RoamingSettings** API 作為字典公開,應用程式可以在其中儲存資料。

Windows.Storage.ApplicationDataContainer roamingSettings = 
   Windows.Storage.ApplicationData.Current.RoamingSettings;  
				   
// Retrivve value from RoamingSettings 
var colorName = roamingSettings.Values["PreferredBgColor"].ToString(); 
 
// Set values to RoamingSettings 
roamingSettings.Values["PreferredBgColor"] = "Green";

當 **RoamingSettings** 中的資料發生變化時,它會觸發 **DataChanged** 事件,您可以在其中重新整理您的設定。

Windows.Storage.ApplicationData.Current.DataChanged += RoamingDataChanged;  

private void RoamingDataChanged(Windows.Storage.ApplicationData sender, object args) {
   // Something has changed in the roaming data or settings 
}

讓我們來看一個示例,在該示例中,我們將設定應用程式的背景顏色,並且這些設定將與 UWP 中提供的漫遊 API 一起漫遊。

以下是新增不同控制元件的 XAML 程式碼。

<Page 
   x:Class = "RoamingSettingsDemo.Views.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:RoamingSettingsDemo.Views" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">
   
   <Grid x:Name = "MainGrid" Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <Grid.RowDefinitions> 
         <RowDefinition Height = "80" /> 
         <RowDefinition /> 
      </Grid.RowDefinitions>
		
      <StackPanel Orientation = "Horizontal" VerticalAlignment = "Top" Margin = "12,12,0,0"> 
         <TextBlock Style = "{StaticResource HeaderTextBlockStyle}"  
            FontSize = "24" Text = "Connected Experience Demo" /> 
      </StackPanel>
		
      <Grid Grid.Row = "1" Margin = "0,80,0,0"> 
         <StackPanel Margin = "62,0,0,0"> 
            <TextBlock x:Name = "textBlock" HorizontalAlignment = "Left"   
               TextWrapping = "Wrap" Text = "Choose your background color:"  
               VerticalAlignment = "Top"/> 
					
            <RadioButton x:Name = "BrownRadioButton" Content = "Brown"  
               Checked = "radioButton_Checked" /> 
					
            <RadioButton x:Name = "GrayRadioButton" Content = "Gray"  
               Checked = "radioButton_Checked"/> 
         </StackPanel> 
      </Grid> 
		
   </Grid> 
	
</Page>			 

下面給出了 **RoamingSettings** 和不同事件的 C# 實現。

using System; 
using System.Collections.Generic; 
using System.IO; 
using System.Linq; 
using System.Runtime.InteropServices.WindowsRuntime; 

using Windows.Foundation; 
using Windows.Foundation.Collections; 

using Windows.UI; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
using Windows.UI.Xaml.Controls.Primitives; 
using Windows.UI.Xaml.Data; 
using Windows.UI.Xaml.Input; 
using Windows.UI.Xaml.Media; 
using Windows.UI.Xaml.Navigation;  

// The RoamingSettingsDemo Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=234238  

namespace RoamingSettingsDemo.Views {

   /// <summary>
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
   
      public MainPage() {
         this.InitializeComponent(); 
      }  
		
      protected override void OnNavigatedTo(NavigationEventArgs e) {
         SetBackgroundFromSettings();  
         Windows.Storage.ApplicationData.Current.DataChanged += RoamingDataChanged; 
      }  
		
      protected override void OnNavigatedFrom(NavigationEventArgs e) {
         Windows.Storage.ApplicationData.Current.DataChanged -= RoamingDataChanged; 
      }  
		
      private void RoamingDataChanged(Windows.Storage.ApplicationData sender, object args) {
	  
         // Something has changed in the roaming data or settings 
         var ignore = Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,  
            () ⇒ SetBackgroundFromSettings()); 
      } 
		
      private void SetBackgroundFromSettings() {
	  
         // Get the roaming settings 
         Windows.Storage.ApplicationDataContainer roamingSettings = 
            Windows.Storage.ApplicationData.Current.RoamingSettings;  
				   
         if (roamingSettings.Values.ContainsKey("PreferBrownBgColor")) {
            var colorName = roamingSettings.Values["PreferBrownBgColor"].ToString();
				
            if (colorName == "Gray") {
               MainGrid.Background = new SolidColorBrush(Colors.Gray); 
               GrayRadioButton.IsChecked = true; 
            } else if (colorName == "Brown") {
               MainGrid.Background = new SolidColorBrush(Colors.Brown); 
               BrownRadioButton.IsChecked = true; 
            } 
         } 
			
      } 
		
      private void radioButton_Checked(object sender, RoutedEventArgs e){ 
         if (GrayRadioButton.IsChecked.HasValue && 
            (GrayRadioButton.IsChecked.Value == true)) {
               Windows.Storage.ApplicationData.Current.RoamingSettings.
                  Values["PreferBrownBgCo lor"] = "Gray"; 
         } else {
            Windows.Storage.ApplicationData.Current.RoamingSettings.
               Values["PreferBrownBgCo lor"] = "Brown"; 
         }  
			
         SetBackgroundFromSettings(); 
      } 
		
   } 
} 		

編譯並執行上述程式碼後,您將看到以下視窗。

Content Experience Execution

讓我們選擇灰色作為背景顏色並關閉此應用程式。

現在,當您在此裝置或任何其他裝置上執行此應用程式時,您將看到背景顏色已更改為灰色。這表明應用程式已成功檢索 **RoamingSettings** 中的背景顏色更改資訊。

Content Experience Demo

Windows 10 開發 - 導航

在通用 Windows 平臺 (UWP) 應用程式中,導航是導航結構、導航元素和系統級功能的靈活模型。它為在應用程式、頁面和內容之間移動提供各種直觀的使用者體驗。

在某些情況下和場景中,所有內容和功能都可以輕鬆地放入單個頁面中,開發人員無需建立多個頁面。但是,在大多數應用程式中,多個頁面用於不同內容和功能之間的互動。

當應用程式具有多個頁面時,開發人員提供正確的導航體驗非常重要。

頁面模型

通常,在通用 Windows 平臺 (UWP) 應用程式中,使用單頁面導航模型。

重要功能包括 -

  • 單頁面導航模型將應用程式的所有上下文以及其他內容和資料維護到一箇中央框架中。

  • 您可以將應用程式的內容劃分為多個頁面。但是,當從一個頁面移動到另一個頁面時,您的應用程式會將頁面載入到主頁面表單中。

  • 您的應用程式的主頁面不會被解除安裝,程式碼和資料也不會被解除安裝,這使得管理狀態變得更容易,並在頁面之間提供更流暢的過渡動畫。

多頁面導航也用於在不同頁面或螢幕之間導航,而無需擔心應用程式上下文。在多頁面導航中,每個頁面都有自己的一組功能、使用者介面和資料等。

多頁面導航通常用於網站內的網頁。

導航結構

在多頁面導航中,每個頁面都有自己的一組功能、使用者介面和資料等。例如,照片應用程式可能有一個頁面用於捕捉照片,然後當用戶想要編輯照片時,它會導航到另一個頁面,並且為了維護圖片庫,它還有另一個頁面。

應用程式的導航結構由這些頁面的組織方式定義。

以下是組織應用程式導航的方法 -

層次結構

在這種型別的導航結構中,

  • 頁面被組織成樹狀結構。

  • 每個子頁面只有一個父頁面,但父頁面可以有一個或多個子頁面。

  • 要到達子頁面,您必須遍歷父頁面。

Hierarchy Structure

同級

在這種型別的導航中 -

  • 頁面並排存在。
  • 您可以按任何順序從一個頁面轉到另一個頁面。
Peer

在大多數多頁面應用程式中,這兩種結構同時使用。一些頁面被組織成同級,而另一些頁面則被組織成層次結構。

讓我們舉一個包含三個頁面的例子。

  • 建立一個名為 **UWPNavigation** 的空白 UWP 應用程式。

  • 透過在**解決方案資源管理器**中右鍵單擊專案並從選單中選擇**新增 > 新建項**選項,新增兩個空白頁面,這將開啟以下對話方塊視窗。

Add New Item
  • 從中間窗格中選擇空白頁面,然後單擊**新增**按鈕。

  • 現在按照上述步驟再新增一個頁面。

您將在解決方案資源管理器中看到三個頁面 - **MainPage、BlankPage1** 和 **BlankPage2**。

下面是 **MainPage** 的 XAML 程式碼,其中添加了兩個按鈕。

<Page 
   x:Class = "UWPNavigation.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPNavigation" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">  
	
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <Hub Header = "Hi, this Main Page"/> 
      <Button Content = "Go to Page 1" Margin = "64,131,0,477" Click = "Button_Click"/>
      <Button Content = "Go to Page 2" Margin = "64,210,0,398" Click = "Button_Click_1"/> 
   </Grid> 
	
</Page>

下面是 **MainPage** 上兩個按鈕的 C# 程式碼,它們將導航到其他兩個頁面。

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;
  
// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  

namespace UWPNavigation {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
      public MainPage() {
         this.InitializeComponent(); 
      }  
		
      private void Button_Click(object sender, RoutedEventArgs e){ 
         this.Frame.Navigate(typeof(BlankPage1)); 
      } 
		
      private void Button_Click_1(object sender, RoutedEventArgs e) {
         this.Frame.Navigate(typeof(BlankPage2)); 
      } 
		
   } 
} 

下面顯示了 **空白頁面 1** 的 XAML 程式碼。

<Page 
   x:Class = "UWPNavigation.BlankPage1" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPNavigation" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
      <Hub Header = "Hi, this is page 1"/> 
      <Button Content = "Go to Main Page" Margin = "64,94,0,514" Click = "Button_Click"/> 
   </Grid> 
	
</Page>

下面顯示了 **空白頁面 1** 上按鈕 - 單擊事件的 C# 程式碼,它將導航到主頁面。

using System; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
 
// The Blank Page item template is documented at
   http://go.microsoft.com/fwlink/?LinkId=234238 
	
namespace UWPNavigation {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class BlankPage1 : Page {
    
      public BlankPage1() {
         this.InitializeComponent(); 
      }
		
      private void Button_Click(object sender, RoutedEventArgs e) {
         this.Frame.Navigate(typeof(MainPage)); 
      }
		
   } 
}

下面是 **空白頁面 2** 的 XAML 程式碼。

<Page 
   x:Class = "UWPNavigation.BlankPage2" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPNavigation" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d"> 
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}">
      <Hub Header = "Hi, this is page 2"/>
      <Button Content = "Go to Main Page" Margin = "64,94,0,514" Click = "Button_Click"/> 
   </Grid> 
	
</Page>

下面是 **空白頁面 2** 上按鈕單擊事件的 C# 程式碼,它將導航到主頁面。

using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls; 
 
// The Blank Page item template is documented at  
   http://go.microsoft.com/fwlink/?LinkId=234238
	
namespace UWPNavigation {

   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary>
	
   public sealed partial class BlankPage2 : Page {
   
      public BlankPage2(){ 
         this.InitializeComponent(); 
      } 
		
      private void Button_Click(object sender, RoutedEventArgs e) {
         this.Frame.Navigate(typeof(MainPage)); 
      }
		
   } 
}

編譯並執行上述程式碼後,您將看到以下視窗。

Compiled and Executed

當您單擊任何按鈕時,它將引導您導航到相應的頁面。讓我們單擊**轉到頁面 1**,將顯示以下頁面。

Compiled and Executed1

當您單擊**“轉到主頁面”**按鈕時,它將導航回主頁面。

Windows 10 開發 - 網路

如今,您會看到許多應用程式,它們以某種方式與網路上的 Web 服務或其他裝置整合。獲取線上天氣內容、最新新聞、聊天或點對點遊戲是一些使用網路服務的示例。這些應用程式使用各種網路 API 構建。在 Windows 10 中,網路 API 在速度和記憶體效能以及它們為開發人員提供的功能和靈活性方面得到了改進。

功能

為了聯網,您必須將相應的許可權元素新增到應用程式清單中。如果應用程式清單中未指定任何網路許可權,則應用程式將沒有任何網路功能,任何嘗試連線到網路的操作都將失敗。

以下是最常用的網路功能。

序號 功能和說明
1

internetClient

提供到 Internet 和公共場所(如機場和咖啡店)網路的出站訪問。大多數需要 Internet 訪問的應用程式都應使用此功能。

2

internetClientServer

允許應用程式從 Internet 和公共場所(如機場和咖啡店)網路進行入站和出站網路訪問。

3

privateNetworkClientServer

允許應用程式在使用者信任的位置(如家庭和工作場所)進行入站和出站網路訪問。

要在應用程式清單檔案中定義一個或多個功能,請檢視下面給出的影像。

Capabilities App

通用 Windows 平臺 (UWP) 透過以下方式包含大量網路 API -

  • 查詢裝置的連線狀態並連線到對等裝置。
  • 與 REST Web 服務通訊,以及
  • 在後臺下載大型媒體檔案

網路技術

在通用 Windows 平臺 (UWP) 中,開發人員可以使用以下網路技術,這些技術可以在許多不同的情況下使用。

套接字

當您希望使用自己的協議與另一臺裝置通訊時,可以使用套接字。

  • 作為通用 Windows 平臺 (UWP) 應用程式開發人員,您可以同時使用 **Windows.Networking.Sockets** 和 **Winsock** 與其他裝置通訊。

  • **Windows.Networking.Sockets** 的優勢在於它是一個現代 API,專為 UWP 開發人員使用而設計。

  • 如果您使用跨平臺網路庫或其他現有的 Winsock 程式碼,則使用 **Winsock API**。

以下程式碼顯示瞭如何建立套接字偵聽器。

try {
 
//Create a StreamSocketListener to start listening for TCP connections. 
   Windows.Networking.Sockets.StreamSocketListener socketListener = new 
      Windows.Networking.Sockets.StreamSocketListener(); 
					  
//Hook up an event handler to call when connections are received. 
   socketListener.ConnectionReceived += SocketListener_ConnectionReceived;
   
//Start listening for incoming TCP connections on the specified port. 
   You can specify any port that's not currently in use. 
	
   await socketListener.BindServiceNameAsync("1337"); 
} catch (Exception e) {
   //Handle exception. 
}

以下程式碼顯示了 **SocketListener_ConnectionReceived** 事件處理程式的實現。

private async void SocketListener_ConnectionReceived(
   Windows.Networking.Sockets.StreamSocketListen er sender, 
   Windows.Networking.Sockets.StreamSocketListenerConnectionReceivedEventArgs args){ 
 
   //Read line from the remote client. 
   Stream inStream = args.Socket.InputStream.AsStreamForRead(); 
   StreamReader reader = new StreamReader(inStream); 
   string request = await reader.ReadLineAsync(); 
	
   //Send the line back to the remote client. 
   Stream outStream = args.Socket.OutputStream.AsStreamForWrite(); 
   StreamWriter writer = new StreamWriter(outStream); 
	
   await writer.WriteLineAsync(request); 
   await writer.FlushAsync(); 
}

WebSocket

**WebSockets** 協議提供了一種在客戶端和伺服器之間透過網路進行快速且安全的雙向通訊的方法。通用 Windows 平臺 (UWP) 開發人員可以使用 **MessageWebSocket** 和 **StreamWebSocket** 類連線到支援 Websocket 協議的伺服器。

重要功能包括 -

  • 在 WebSocket 協議下,資料會立即透過全雙工單套接字連線傳輸。

  • 它允許即時從兩個端點發送和接收訊息。

  • **WebSockets** 非常適合用於即時遊戲,在即時遊戲應用中需要安全且使用快速資料傳輸來實現即時的社交網路通知和資訊的最新顯示(遊戲統計資料)。

以下程式碼顯示瞭如何在安全連線上傳送和接收訊息。

MessageWebSocket webSock = new MessageWebSocket(); 
 
//In this case we will be sending/receiving a string so we need to 
   set the MessageType to Utf8. 
webSock.Control.MessageType = SocketMessageType.Utf8;  

//Add the MessageReceived event handler. 
webSock.MessageReceived += WebSock_MessageReceived;  

//Add the Closed event handler. 
webSock.Closed += WebSock_Closed; 
 
Uri serverUri = new Uri("wss://echo.websocket.org");
  
try {
   //Connect to the server. 
   await webSock.ConnectAsync(serverUri);
	
   //Send a message to the server. 
   await WebSock_SendMessage(webSock, "Hello, world!"); 
} catch (Exception ex) { 
   //Add code here to handle any exceptions 
} 

以下程式碼顯示了事件實現,該實現將從已連線的 **WebSocket** 接收字串。

//The MessageReceived event handler. 
private void WebSock_MessageReceived(MessageWebSocket sender, 
   MessageWebSocketMessageReceivedEventArgs args){ 

   DataReader messageReader = args.GetDataReader(); 
   messageReader.UnicodeEncoding = UnicodeEncoding.Utf8; 
   string messageString = messageReader.ReadString(
      messageReader.UnconsumedBufferLength);  
   //Add code here to do something with the string that is received. 
}

HttpClient

**HttpClient** 和 **Windows.Web.Http** 名稱空間 API 使開發人員能夠使用 HTTP 2.0 和 HTTP 1.1 協議傳送和接收資訊。

它可以用於 -

  • 與 Web 服務或 Web 伺服器通訊。
  • 上傳或下載大量小檔案。
  • 透過網路流式傳輸內容。

以下程式碼顯示瞭如何使用 **Windows.Web.Http.HttpClient** 和 **Windows.Web.Http.HttpResponseMessage** 傳送 GET 請求。

//Create an HTTP client object 
Windows.Web.Http.HttpClient httpClient = new Windows.Web.Http.HttpClient(); 
 
//Add a user-agent header to the GET request.  
var headers = httpClient.DefaultRequestHeaders;

//The safe way to add a header value is to use the TryParseAdd method 
   and verify the return value is true, 
	
//especially if the header value is coming from user input. 
string header = "ie"; 

if (!headers.UserAgent.TryParseAdd(header)) {
   throw new Exception("Invalid header value: " + header); 
}  

header = "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)";
 
if (!headers.UserAgent.TryParseAdd(header)) {
   throw new Exception("Invalid header value: " + header); 
}  

Uri requestUri = new Uri("http://www.contoso.com"); 
 
//Send the GET request asynchronously and retrieve the response as a string. 
Windows.Web.Http.HttpResponseMessage httpResponse = new
   Windows.Web.Http.HttpResponseMessage(); 
string httpResponseBody = ""; 
 
try {
   //Send the GET request 
   httpResponse = await httpClient.GetAsync(requestUri); 
   httpResponse.EnsureSuccessStatusCode(); 
   httpResponseBody = await httpResponse.Content.ReadAsStringAsync(); 
} catch (Exception ex) {
   httpResponseBody = "Error: " + ex.HResult.ToString("X") + " Message: " + ex.Message; 
} 

Windows 10 開發 - 雲服務

作為開發者,您可能需要訪問桌面以外的資料。雲服務可以幫助您訪問這些資料。本章將更深入地瞭解您可能需要的雲服務。

微軟提供了一個雲計算平臺和基礎設施,稱為Microsoft Azure,您可以在其中構建、部署和管理所有應用程式和服務。

Azure 最初於 2010 年 2 月 1 日作為 Windows Azure 釋出。後來於 2014 年 3 月 25 日更名為 Microsoft Azure。

它提供PaaS 和 IaaS服務,並支援多種不同的程式語言、工具和框架,包括微軟專有和第三方軟體及系統。

微軟使用 Windows 10 升級了雲服務。雖然OneDrive自 2007 年就已存在,但在 Windows 8 中引入了 Microsoft 帳戶整合。對於 Windows 10,這兩項服務都進行了更新,增加了整合和新功能,吸引了更多使用者。

Microsoft 帳戶

您可以使用您的 Microsoft 帳戶使用 Microsoft 的 Azure 雲服務。當然,它不是免費的,但您可以使用 30 天免費試用。

首次使用 Windows 10 設定機器並使用 Microsoft 帳戶登入時,您可以使用同一帳戶訂閱 Microsoft Azure。要註冊 Microsoft Azure,請點選此處 https://azure.microsoft.com/.

訂閱 Microsoft Azure 後,轉到 Azure 門戶 https://portal.azure.com/。您將看到以下頁面。

Microsoft Azure

您可以在資料庫中儲存資料,使用虛擬機器等。您還可以構建和託管移動應用程式的後端。

讓我們透過以下步驟,用一個示例來嘗試一下。

  • 點選左側窗格中的新建選項。

New Microsoft Azure
  • 選擇Web + 移動 > 移動應用,併為您的 Web 應用命名。

Mobile App
  • 提交和部署您的應用需要一些時間。此過程完成後,您將看到以下頁面。在這裡,您可以選擇不同型別的移動應用,例如 Windows(C#)、iOS Android 等。

Select Mobile App
  • 由於我們正在討論 Windows 10,因此選擇 Windows (C#),這將開啟以下頁面。

Select Window
  • 在這裡,您可以看到兩個下載選項。這些是示例專案,您可以簡單地下載並在 Visual Studio 中構建,然後可以輕鬆釋出到 Microsoft Azure。

  • 讓我們下載第一個,它是一個伺服器專案。它是一個 zip 檔案。

  • 下載完成後,解壓縮並開啟 Visual Studio。

  • 現在,構建此應用程式。如果列出了某些錯誤,則再次構建它。

  • 執行應用程式。您將看到以下網頁,它現在位於本地主機上。

Run Application
  • 現在,要將此應用程式託管在雲端,請右鍵單擊解決方案資源管理器中所示的專案選項。

Project Option
  • 從選單中選擇釋出選項。您將看到以下對話方塊。

Publish Option
  • 選擇第一個選項 - Microsoft Azure Web 應用。將開啟以下對話方塊。

Microsoft Azure Web Apps
  • 現在,從選單中點選新增帳戶選項以新增 Microsoft Azure 帳戶。

Add Microsoft Azure Account
  • 指定您的憑據並點選登入。將開啟以下對話方塊視窗。

  • 登入後,從選單現有 Web 應用中選擇您的應用程式,然後點選確定

Existing Web Apps
  • 下面顯示的對話方塊顯示了一些與您的應用程式相關的資訊,例如名稱、伺服器名稱、URL 等。

UWP Cloud Demo
  • 現在,點選驗證連線按鈕。驗證後,點選釋出按鈕,您將看到您的應用程式現在已託管在Microsoft Azure上。

Validate Connection

Windows 10 開發 - 即時磁貼

在本章中,我們將討論透過磁貼與使用者的互動。它是 Windows 10 的標誌性部分。磁貼顯示在開始螢幕以及開始選單上。換句話說,它是在整個 Windows 10 作業系統中以各種形式出現的應用程式圖示資產。它們是通用 Windows 平臺 (UWP) 應用的名片。

磁貼結構

磁貼有三種狀態。

  • 基本狀態 - 開始磁貼的基本元件包括背板、圖示和應用標題。

Basic State
  • 半即時狀態 - 它與基本磁貼相同,唯一的區別是徽章(一個數字)可以顯示 0-99 的數字。

Semi-Live state
  • 即時狀態 - 此磁貼包含半即時狀態磁貼的所有元素,還顯示其他內容板,您可以在其中放置任何內容,例如照片、文字等。

更新磁貼

有四種方法可以更新磁貼。

  • 計劃 - 您可以使用ScheduledTileNotification設定模板和時間。

  • 週期性 - 當從 URI 檢索資訊時,您可以指定一段時間後拉取資訊的時間,例如 30 分鐘、1 小時、6 小時等。

  • 本地 - 本地磁貼可以從您的應用程式更新;可以來自前臺或後臺應用程式。

  • 推送 - 它透過從伺服器推送資訊來更新。

要建立磁貼,請遵循以下程式碼。

var tileXml = 
   TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquare150x150Text01); 
 
var tileAttributes = tileXml.GetElementsByTagName("text"); 
tileAttributes[0].AppendChild(tileXml.CreateTextNode("Hello"));
			
var tileNotification = new TileNotification(tileXml);			
TileUpdateManager.CreateTileUpdaterForApplication().Update(tileNotification);

更新徽章非常簡單,因為它只是一個數字,您可以設定徽章的值,如下所示。

var type = BadgeTemplateType.BadgeNumber; 
var xml = BadgeUpdateManager.GetTemplateContent(type);  

var elements = xml.GetElementsByTagName("badge"); 
var element = elements[0] as Windows.Data.Xml.Dom.XmlElement; 
element.SetAttribute("value", "7");
  
var updator = BadgeUpdateManager.CreateBadgeUpdaterForApplication(); 
var notification = new BadgeNotification(xml); 
updator.Update(notification);

讓我們在 Visual Studio 中建立一個新的 UWP 專案。

  • 您將在解決方案資源管理器中的Assets資料夾下看到不同的 png 檔案。

Assets Folder
  • 讓我們在包清單中定義預設磁貼及其影像。

  • 雙擊package.appxmanifest。這將開啟清單編輯器視窗。

  • 您可以為應用程式磁貼選擇任何指定尺寸的影像和圖示。在磁貼影像和徽標下,為所有徽標提供了預設影像,例如

Visual Assets
  • 選擇視覺資產選項卡。

    • 方形 71x71 徽標
    • 方形 150x150 徽標
    • 方形 310x310 徽標
    • 商店徽標
  • 執行應用程式,然後轉到開始螢幕,您將看到應用程式的磁貼。

Execute Your Application

Windows 10 開發 - 共享契約

在本章中,我們將學習如何在應用程式之間共享資料。使用者經常會遇到他們很想與他人分享或在另一個應用程式中使用資訊。如今,使用者希望使用技術與他人聯絡和共享。

使用者可能希望共享 -

  • 與他們的社交網路分享連結
  • 將圖片複製到報告中
  • 將檔案上傳到雲端儲存

如今,應用程式需要確保它們使用的資料也可供使用者共享和交換。共享是一個輕量級功能,易於新增到您的 UWP 應用程式中。應用程式有多種方法可以與其他應用程式交換資料。

在 UWP 應用程式中,可以透過以下方式支援共享功能;

  • 首先,應用程式可以是源應用程式,提供使用者想要共享的內容。

  • 其次,應用程式可以是目標應用程式,使用者將其選擇為共享內容的目標。

  • 應用程式也可以同時是源應用程式和目標應用程式。

共享內容

從應用程式(即源應用程式)共享內容非常簡單。要執行任何共享操作,您將需要DataPackage類物件。此物件包含使用者想要共享的資料。

DataPackage物件可以包含以下型別的內容 -

  • 純文字
  • 統一資源識別符號 (URI)
  • HTML
  • 格式化文字
  • 點陣圖
  • 檔案
  • 開發者定義的資料

共享資料時,您可以包含上述格式中的一種或多種。要在應用程式中支援共享,您首先需要獲取DataTransferManager類的例項。

然後,它將註冊一個事件處理程式,該處理程式在每次發生DataRequested事件時呼叫。

DataTransferManager dataTransferManager = DataTransferManager.GetForCurrentView(); 
dataTransferManager.DataRequested += new TypedEventHandler<DataTransferManager, 
   DataRequestedEventArgs>(this.ShareTextHandler);

當您的應用收到DataRequest物件時,您的應用程式就可以新增使用者想要共享的內容了。

private void ShareTextHandler(DataTransferManager sender, DataRequestedEventArgs e){
   DataRequest request = e.Request;
	
   // The Title is mandatory 
   request.Data.Properties.Title = "Share Text Example"; 
   request.Data.Properties.Description = "A demonstration that shows how to share text."; 
   request.Data.SetText("Hello World!"); 
}

您的應用程式共享的任何內容都必須包含兩個屬性 -

  • 標題屬性,它是必需的,必須設定。
  • 內容本身。

接收共享內容

如果您希望您的應用程式能夠接收共享內容,那麼您需要做的第一件事就是宣告它支援共享契約。聲明後,系統將允許您的應用程式接收內容。

要新增共享契約的支援 -

  • 雙擊package.appmanifest檔案。

  • 轉到宣告選項卡。從可用宣告列表中選擇共享目標,然後點選新增按鈕。

Share Target
  • 如果您希望您的應用程式接收任何型別的檔案作為共享內容,則可以指定檔案型別和資料格式。

  • 要指定您支援的資料格式,請轉到宣告頁面的資料格式部分,然後點選新增新

  • 鍵入您支援的資料格式的名稱。例如,“文字”

  • 要指定您支援的檔案型別,請在宣告頁面的支援的檔案型別部分點選新增新

  • 鍵入您要支援的檔名副檔名,例如.pdf

  • 如果您希望支援所有檔案型別,請選中支援任何檔案型別複選框。

Support All Files
  • 當用戶選擇您的應用程式作為共享資料的目標應用程式時,將觸發OnShareTargetActivated事件。

  • 您的應用程式需要處理此事件以處理使用者想要共享的資料。

protected override async void OnShareTargetActivated(ShareTargetActivatedEventArgs args) { 
   // Code to handle activation goes here.  
}
  • 使用者想要與任何應用程式共享的所有資料都包含在ShareOperation物件中。您還可以檢查它包含的資料的格式。

下面是處理以純文字格式共享內容的程式碼片段。

ShareOperation shareOperation = args.ShareOperation;
 
if (shareOperation.Data.Contains(StandardDataFormats.Text)) {
   string text = await shareOperation.Data.GetTextAsync(); 
   
   // To output the text from this example, you need a TextBlock control 
   // with a name of "sharedContent". 
   sharedContent.Text = "Text: " + text; 
}

讓我們透過建立一個新的 UWP 專案來檢視一個簡單的示例,該專案將共享一個網頁連結。

下面是 XAML 程式碼,其中建立了一個具有某些屬性的按鈕。

<Page 
   x:Class = "UWPSharingDemo.MainPage" 
   xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
   xmlns:x = "http://schemas.microsoft.com/winfx/2006/xaml" 
   xmlns:local = "using:UWPSharingDemo" 
   xmlns:d = "http://schemas.microsoft.com/expression/blend/2008" 
   xmlns:mc = "http://schemas.openxmlformats.org/markup-compatibility/2006" 
   mc:Ignorable = "d">
   
   <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}"> 
	
      <StackPanel Orientation = "Vertical"> 
         <TextBlock Text = "Share Web Link" Style = "{StaticResource 
            HeaderTextBlockStyle}" Margin = "30"></TextBlock> 
				
         <Button Content = "Invoke share contract" Margin = "10"
            Name = "InvokeShareContractButton" Click = "InvokeShareContractButton_Click"
            ></Button> 
      </StackPanel>
		
   </Grid> 
	
</Page>

下面是 C# 程式碼,其中實現了按鈕點選事件,並給出了 URI 共享程式碼。

using System; 

using Windows.ApplicationModel.DataTransfer; 
using Windows.UI.Xaml; 
using Windows.UI.Xaml.Controls;  

// The Blank Page item template is documented at 
   http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409  
	
namespace UWPSharingDemo {
 
   /// <summary> 
      /// An empty page that can be used on its own or navigated to within a Frame. 
   /// </summary> 
	
   public sealed partial class MainPage : Page {
    
      DataTransferManager dataTransferManager;
		
      public MainPage() {
         this.InitializeComponent(); 
         dataTransferManager = DataTransferManager.GetForCurrentView();  
         dataTransferManager.DataRequested += dataTransferManager_DataRequested; 
      }
		
      void dataTransferManager_DataRequested(DataTransferManager sender,
         DataRequestedEventArgs args) { 
            Uri sharedWebLink = new Uri("https://msdn.microsoft.com");
				
            if (sharedWebLink != null) {
               DataPackage dataPackage = args.Request.Data; 
               dataPackage.Properties.Title = "Sharing MSDN link"; 
				
               dataPackage.Properties.Description = "The Microsoft Developer Network (MSDN)
                  is designed to help developers write applications using Microsoft 
                  products and technologies.";
					
               dataPackage.SetWebLink(sharedWebLink); 
            } 
      }
		
      private void InvokeShareContractButton_Click(object sender, RoutedEventArgs e) {
         DataTransferManager.ShowShareUI(); 
      }
		
   } 
} 

編譯並執行上述程式碼後,您將在模擬器上看到以下頁面。

Compiled And Executed

點選按鈕後,它將提供在哪個應用程式上共享的選項。

Share Application

點選訊息,將顯示以下視窗,您可以從中將連結傳送給任何人。

Receiving Application

Windows 10 開發 - 移植到 Windows

在本章中,我們將學習如何將您現有的 Windows 8.1 應用程式移植到通用 Windows 平臺 (UWP)。您可以建立一個單個 Windows 10 應用包,您的客戶可以將其安裝到所有型別的裝置上。

將您的應用程式移植到 Windows 10 UWP 後,您的應用程式將受益於 -

  • 令人興奮的新硬體
  • 巨大的獲利機會

  • 一套現代化的 API 集,
  • 自適應 UI 控制元件,
  • 自適應設計和程式碼
  • 一系列的輸入方式,例如滑鼠、鍵盤、觸控和語音。

將 Windows 8.x 專案移植到 UWP 專案

有兩種方法可以將現有的 Windows 8.x 應用程式移植到通用 Windows 平臺 (UWP)。

選項 1 − 一種是在 Visual Studio 中建立一個新的 Windows 10 專案,並將您的檔案複製到其中。

選項 2 − 另一種方法是編輯現有專案檔案的副本,包括應用包清單。

以下是使用第一種選項時的主要步驟。

  • 啟動 Microsoft Visual Studio 2015 並建立一個名為 UWPBookStore 的新的空白應用程式 (Windows 通用) 專案。

  • 您的新專案構建一個應用包(一個 appx 檔案),該檔案將在所有裝置系列上執行。

  • 在您的通用 8.1 應用專案中,識別您想要重用的所有原始碼檔案和視覺資產檔案。下面顯示了一個示例應用程式,它有三個專案。一個用於 Windows,第二個用於移動裝置,第三個是 Windows 和移動裝置的共享專案。

  • 在手機上執行此應用程式後,您將看到以下視窗。

Application on Phone
  • 執行 Windows 應用程式後,您將看到以下應用程式。

Windows Application
  • 現在,開啟新建立的 UWP 專案應用程式
UWP Project Application
  • 從共享專案中,複製包含書籍封面影像 (.png) 檔案的資料夾 Assets\CoverImages。還複製 ViewModel 資料夾和 MainPage.xaml 並替換目標檔案。

  • 從 Windows 專案中,複製 BookstoreStyles.xaml。此檔案中的所有資源鍵都將在 Windows 10 應用中解析。等效的 WindowsPhone 檔案中的一些資源鍵將無法解析。

  • 解決方案資源管理器 中,確保 顯示所有檔案 切換為 開啟

Solution Explorer
  • 選擇您複製的檔案,右鍵單擊它們,然後單擊 包含在專案中,如下所示。

Include In Project
  • 這將自動包含它們包含的資料夾。然後,如果需要,您可以將 顯示所有檔案 切換為 關閉

  • 現在,您的專案結構將在 解決方案資源管理器 中如下所示。

Project Structure
  • 編輯您剛剛複製的原始碼和標記檔案,並將對 Bookstore1_81 名稱空間的任何引用更改為 UWPBookStore 名稱空間。

  • 最簡單的方法是使用 在檔案中替換 功能替換名稱空間。檢視模型中不需要進行任何程式碼更改。

  • 現在,執行上述程式碼後,您可以在本地計算機上執行它,也可以在移動裝置上執行它,如下所示。

Execute On Local Machine Run On Local Machine

現在,第二個選項是編輯現有專案檔案的副本,包括應用包清單。將 Windows/phone 8.x 移植到 Windows 10 時,專案檔案和 package.appmanifest 檔案需要進行一些修改。

Microsoft 提供了 UWP 專案升級實用程式,在移植現有應用程式時非常有用。該實用程式可以從 github.com 下載。

我們建議您逐步按照上述示例操作,以便更好地理解。

廣告

© . All rights reserved.