Windows10-development-quick-guide
Windows 10開発-はじめに
このチュートリアルは、Windows 10アプリケーションの開発方法を学びたい人向けに設計されています。 このチュートリアルでは、学習します-
- Windows 10アプリケーション開発
- Microsoftがリリースした新しいOSの更新
- アップデートの開発者向けの新機能
最初のリリースでは利用できなかった多くの興味深いアプリシナリオが可能になりました。 Microsoftは新しいAPIを追加しただけでなく、既存のAPIも拡張しました。
ユニバーサルWindowsアプリ
ユニバーサルWindowsアプリは、Windows 8で最初にWindowsランタイムとして導入され、ユニバーサルアプリケーションプラットフォーム上に構築されました。
現在、Windows 10では、ユニバーサルアプリケーションプラットフォームの名前がユニバーサルWindowsプラットフォーム(UWP)に変更されています。 PC、タブレット、電話など、Windowsストア用のWindows 10デバイスを対象とすることで、最新の完全没入型アプリを構築できます。
Windows 10では、Windows 10でサポートされるすべてのデバイスに到達するためのアプリケーションを簡単に開発できます。
- 1つのAPIセット
- 1つのアプリパッケージ
- そして1店舗
ユニバーサルWindowsプラットフォームは、さまざまな画面サイズと、タッチパッド、マウスとキーボード、ゲームコントローラー、ペンなどのさまざまな相互作用モデルもサポートしています。
UWPアプリの特徴
以下は、Windows 10よりも優れたユニバーサルWindowsアプリの特徴の一部です。
- Windows 8.1のようなOSではなく、デバイスファミリをターゲットにできます。
- アプリは、*。AppX *パッケージ形式を使用してパッケージ化および配布されます。これにより、アプリをシームレスに展開および更新できます。
- アプリケーションをWindowsストアに送信すると、すべてのデバイスファミリで、または選択したデバイスのみで利用できるようになります。 Windowsデバイス用のすべてのアプリを1か所で簡単に管理できます。
- アプリケーションの可用性を特定のデバイスファミリに制限できます。
- ユニバーサルWindowsプラットフォーム(UWP)のコアAPIは、すべてのWindowsデバイスファミリで同じです。 そのため、コアAPIのみを使用するアプリであれば、すべてのWindows 10デバイスで実行できます。
- Extension 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 8でWindowsランタイムとして初めて導入されたユニバーサルWindowsプラットフォーム(UWP)上に構築されます。 Windows 10では、ユニバーサルWindowsプラットフォーム(UWP)が導入され、Windowsランタイム(WinRT)モデルがさらに進化しました。
- Windows 8.1では、Universal Windows 8アプリの助けを借りて、Windows Phone 8.1アプリケーションとWindows 8.1アプリケーションの間で初めてWinRTが調整され、共有コードベースを使用してWindows PhoneとWindowsアプリケーションの両方がターゲットになりました。
- 現在Windows Coreとして知られているWindows 10 Unified Coreは、UWPがWindows 10で実行されるすべてのデバイスで利用可能な共通アプリプラットフォームを提供するようになりました。
- UWPは、すべてのデバイスに共通のWinRT APIを呼び出すだけでなく、アプリが実行されているデバイスファミリに固有のAPI(Win32および.NET APIを含む)も呼び出すことができます。
Windows 10でサポートされるデバイス
Windows 8.1およびWindows Phone 8.1アプリはOSを対象としています。 WindowsまたはWindows Phoneのいずれか。 Windows 10アプリケーションはOSをターゲットにしませんが、1つ以上のデバイスファミリをターゲットにします。
デバイスファミリにも独自のAPIがあり、特定のデバイスファミリに機能を追加します。 Windowsストアからアプリケーションをインストールして実行できるデバイスファミリ内のすべてのデバイスを簡単に判別できます。 デバイスファミリの階層表現を次に示します。
UWPの利点
ユニバーサルWindowsプラットフォーム(UWP)は、開発者にいくつかのことを提供します。 彼らは-
- すべてのデバイスに対して1つのオペレーティングシステムと1つの統合コア。
- すべてのファミリでアプリケーションを実行する1つのアプリプラットフォーム。
- アプリケーションとダッシュボードを送信する1つの開発センター。
- すべてのデバイス用の1つのストア。
UWP開発のセットアップ
Windows 10用の独自のユニバーサルWindowsプラットフォーム(UWP)アプリの作成を開始するには、次の手順に従う必要があります。
- Windows 10 OS -UWPアプリを開発するには、最新バージョンのWindowsが必要です。 Windows 8.1でUWPアプリケーションを開発することもできますが、UIデザイナーウィンドウはサポートされていません。
- * Windows 10開発者ツール*-Visual Studio 2015では、UWPアプリを設計、コーディング、テスト、およびデバッグできます。 [[1]] Visual Studio Community 2015をダウンロードしてインストールできます。
- * Windows 10の開発モードを有効にします*-
- [スタート]> [設定] に移動します。
- [更新とセキュリティ]を選択します。
- 次に、「開発者向け」*を選択します。
- *開発者モード*をクリックします
UWPアプリの場合、デバイスでアプリケーションをテストすることが重要です。
- アプリ開発者として登録-アプリの開発を開始できますが、アプリをストアに送信するには、開発者アカウントが必要です。 ここで開発者アカウントを作成できます* https://msdn.microsoft.com/enus/library/windows/apps/bg124287.aspx*
上記の手順を実行した後、ユニバーサルWindowsプラットフォーム(UWP)アプリケーションの開発を開始する準備ができました。
Windows 10開発-最初のアプリ
この章では、Windows 10でXAMLとC#を使用して、ユニバーサルWindowsプラットフォーム(UWP)で最初のシンプルなアプリケーション "Hello world" を作成します。 Visual Studioで作成された単一のUWPアプリケーションをWindows 10デバイスで実行および実行する方法を示します。
以下の手順に従って、アプリの作成を開始しましょう。
- Visual Studio 2015を起動します。
- *ファイル*メニューをクリックし、*新規>プロジェクト*を選択します。
- 次の[新しいプロジェクト]ダイアログウィンドウが表示されます。 ダイアログボックスの左ペインにさまざまなタイプのテンプレートが表示されます。
*左ペインに、ツリービューが表示されます。* [テンプレート]> [Visual C#]> [Windows *]から[*ユニバーサルテンプレート*]を選択します。
* 中央のペインから、* Blank App(Universal Windows)*テンプレートを選択します
* [*名前]フィールドに *UWPHelloWorld* と入力して、プロジェクトに名前を付けます。
* [OK]をクリックして、新しいUWPプロジェクトを作成します。
- Solution Explorer で新しく作成されたプロジェクトを確認できます。
- これは空のアプリですが、多くのファイルが含まれているため、UWPアプリケーションの最小要件です。
- MainPage.xaml および MainPage.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プロジェクトでは、 Design Window で device preview オプションを使用できます。このオプションを使用して、レイアウトを簡単に変更し、対象とするデバイスファミリのすべてのデバイスの画面サイズに合わせることができます。応用。
- ローカルマシン、シミュレーター、エミュレーター、またはリモートデバイスでアプリを実行およびテストできます。 以下に示すように、次のメニューからターゲットデバイスを選択できます-
- ローカルマシンで上記のコードを実行すると、次のウィンドウが表示されます。 ここで、テキストボックスに任意の名前を入力し、 Click Me ボタンをクリックします。
- これで、エミュレータでアプリをテストする場合、メニューから特定のエミュレータを選択して、アプリケーションを実行できます。 次のエミュレータが表示されます-
上記のアプリケーションを異なるデバイスで実行することをお勧めします。
Windows 10開発-ストア
開発者にとってのWindowsストアの利点は、アプリケーションを販売できることです。 すべてのデバイスファミリに対して単一のアプリケーションを送信できます。
- ユーザーがアプリケーションを見つけることができるように、Windows 10ストアはアプリケーションが送信される場所です。
- Windows 8では、ストアはアプリケーションのみに制限され、マイクロソフトは多くのストアを提供しています。 Xbox Music Store、Xbox Game Storeなど。
- Windows 8ではこれらはすべて異なるストアでしたが、Windows 10ではWindowsストアと呼ばれます。 ユーザーがすべてのWindows 10デバイス用に1か所でアプリ、ゲーム、曲、映画、ソフトウェア、サービスの全範囲を見つけることができるように設計されています。
収益化
収益化とは、デスクトップ、モバイル、タブレット、その他のデバイスでアプリを販売することです。 Windowsストアでアプリケーションやサービスを販売してお金を稼ぐには、さまざまな方法があります。
次の方法のいずれかを選択できます-
- 最も簡単な方法は、有料ダウンロードオプションを使用してストアにアプリを送信することです。
- ユーザーが機能を制限して購入する前にアプリケーションを試すことができるTrailsオプション。
- Microsoft Advertisingを使用して、アプリに広告を追加します。
マイクロソフト広告
広告をアプリケーションに追加し、ユーザーがその特定の広告をクリックすると、広告主がお金を支払います。 Microsoft Advertisingを使用すると、開発者はMicrosoft Advertising Networkから広告を受信できます。
ユニバーサルWindowsアプリ用のMicrosoft Advertising SDKは、Visual Studio 2015によってインストールされるライブラリに含まれています。
visualstudiogalleryからインストールすることもできます。
これで、動画広告とバナー広告をアプリに簡単に統合できます。
*AdControl* を使用してアプリケーションにバナー広告を追加する、XAMLの簡単な例を見てみましょう。
UWPBannerAd という名前の新しいユニバーサルWindows空アプリプロジェクトを作成します。
Solution Explorer で、 References を右クリックします。
- [参照の追加]を選択すると、[参照マネージャー]ダイアログが開きます。
- 左側のウィンドウから、[ユニバーサルWindows]オプションの下にある[拡張機能]を選択し、 *Microsoft Advertising SDK for XAML をチェックします。
- [OK]をクリックして続行します。
- 以下に、 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サイトが開きます。
アプリケーションに*ビデオバナー*を追加することもできます。 [広告を表示]ボタンをクリックすると、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();
}
}
}
}
上記のコードをコンパイルしてローカルマシンで実行すると、次のウィンドウが表示されます。このウィンドウには、[広告の表示]ボタンがあります。
これで、[広告を表示]ボタンをクリックすると、アプリで動画が再生されます。
Windows 10開発-XAMLコントロール
XAMLは、拡張可能なアプリケーションマークアップ言語の略です。 これはユーザーインターフェイスフレームワークであり、WindowsのUI開発をサポートするコントロールの広範なライブラリを提供します。 それらの一部には、Button、Textbox、TextBlockなどの視覚的な表現があります。他のコントロールは、画像などの他のコントロールまたはコンテンツのコンテナとして使用されます すべてのXAMLコントロールは、*“ System.Windows.Controls.Control” *から継承されます。
XAMLエマージングストーリー
XAMLは、Windows Presentation Foundation(WPF)、Silverlight、現在のWindowsアプリなど、多くの重要なMicrosoftプラットフォームで使用されています。 現在、Microsoft Office 2016はUWPアプリのファミリーでもあります。 XAMLはリッチなプラットフォームであり、UWPアプリケーションで使用できる非常に優れた機能とコントロールを提供します。
コントロールの完全な継承階層を以下に示します。
レイアウトコントロール
コントロールのレイアウトは、アプリケーションのユーザビリティにとって非常に重要かつ重要です。 アプリケーションでGUI要素のグループを配置するために使用されます。 レイアウトパネルを選択する際に考慮すべき特定の重要な事項があります-
- 子要素の位置。
- 子要素のサイズ。
- 重なり合っている子要素を互いの上に重ねます。
- レイアウトコントロール*のリストは以下のとおりです-
以下に一般的に使用されるレイアウトコントロールを示します。
S.No. | Controls & Description |
---|---|
1 |
StackPanel
|
2 |
WrapPanel
|
3 |
DockPanel
|
4 |
Canvas
|
5 |
Grid グリッド*は、行と列で構成される柔軟な領域を提供します。 グリッドでは、子要素を表形式で配置できます。 *Grid.Row および Grid.Column プロパティを使用して、特定の行および列に要素を追加できます。 |
6 |
SplitView
|
7 |
RelativePanel
|
8 |
ViewBox
|
9 |
FlipView
|
10 |
GridView
|
UIコントロール
以下は、エンドユーザーに表示されるUIコントロールのリストです。
以下に一般的に使用されるUIコントロールを示します。
S.No. | UI Controls & Description |
---|---|
1 |
Button ユーザー入力に応答するコントロール |
2 |
Calendar ユーザーが視覚的なカレンダー表示を使用して日付を選択できるようにするコントロールを表します。 |
3 |
CheckBox ユーザーが選択またはクリアできるコントロール。 |
4 |
ComboBox ユーザーが選択できるアイテムのドロップダウンリスト。 |
5 |
ContextMenu この要素内からユーザーインターフェイス(UI)を介してコンテキストメニューが要求されるたびに表示されるコンテキストメニュー要素を取得または設定します。 |
6 |
DataGrid カスタマイズ可能なグリッドにデータを表示するコントロールを表します。 |
7 |
DatePicker ユーザーが日付を選択できるようにするコントロール。 |
8 |
Dialogs アプリケーションは、ユーザーが重要な情報を収集または表示するために追加のウィンドウを表示することもあります。 |
9 |
Flyout 情報であるか、ユーザーの操作を必要とする軽量UIを表示するコントロールを表します。 ダイアログとは異なり、フライアウトの外側をクリックまたはタップする、デバイスの戻るボタンを押す、または「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;
}
}
}
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます-
左上のハンバーガーボタンをクリックすると、 SplitView ペインが開閉します。
*SplitView* ペインで、 *Flyout* 、 *MenuFlyout* および *FlipView* コントロールを確認できます。
*SplitView* コンテンツでは、ハイパーリンク、相対パネル、ViewBox、その他のボタンおよびテキストボックスコントロールを確認できます。
Windows 10開発-データバインディング
データバインディングはXAMLアプリケーションのメカニズムであり、Windowsランタイムアプリが部分クラスを使用してデータを表示および操作するシンプルで簡単な方法を提供します。 データの管理は、このメカニズムでのデータの表示方法から完全に分離されています。
データバインディングにより、ユーザーインターフェイス上のUI要素とデータオブジェクト間のデータフローが可能になります。 バインディングが確立され、データまたはビジネスモデルが変更されると、更新が自動的にUI要素に反映され、その逆も同様です。 標準のデータソースではなく、ページ上の別の要素にバインドすることもできます。 データバインディングはすることができます-
- 一方向のデータバインディング
- 双方向のデータバインディング
- 要素のバインド
一方向データバインディング
一方向バインディングでは、データはソース(データを保持するオブジェクト)からターゲット(データを表示するオブジェクト)にバインドされます。
一方向のデータバインディングの簡単な例を見てみましょう。 以下に、いくつかのプロパティを使用して4つのテキストブロックが作成される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>
2つのテキストブロックのTextプロパティは*” Name” および” Title” *に静的に設定され、テキストブロックの他の2つのTextプロパティはEmployeeクラスのクラス変数である“ Name”および“ Title”にバインドされます以下に示すように。
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オブジェクト*が初期化され、その従業員オブジェクトを返す静的メソッドが1つあります。 したがって、プロパティName、Titleにバインドしていますが、プロパティが属するオブジェクトはまだ選択していません。 簡単な方法は、オブジェクトを DataContext に割り当てることです。このプロパティのプロパティは MainPage コンストラクターでバインドします。
このアプリケーションを実行すると、 MainWindow で、そのEmployeeオブジェクトの名前と役職に正常にバインドされていることがすぐにわかります。
双方向のデータバインディング
双方向バインディングでは、ユーザーはユーザーインターフェイスを介してデータを変更し、そのデータをソースで更新できます。 たとえば、ユーザーがビューを見ているときにソースが変更された場合、ビューを更新する必要があります。
2つのラベル、2つのテキストボックス、1つのボタンがいくつかのプロパティとイベントとともに作成される、以下の例を見てみましょう。
<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>
私たちは次を観察することができます-
- 両方のテキストボックスのテキストプロパティは、以下に示すように* Personクラス*のクラス変数である "Name" および "Age" にバインドします。
- * Personクラス*には、NameとAgeという2つの変数があり、そのオブジェクトは MainWindow クラスで初期化されます。
- XAMLコードでは、プロパティにバインドしています- Name および Age ですが、プロパティが属するオブジェクトを選択していません。
- より簡単な方法は、オブジェクトを DataContext に割り当てることです。このオブジェクトのプロパティは、以下の MainWindowconstructor に示すように、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 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;
}
}
}
}
}
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。 [表示]ボタンをクリックします。
名前と年齢を変更し、[表示]ボタンをもう一度クリックします。
クリックボタン*「表示」では、 *TextBlock のデータを表示するためにテキストボックスのテキストは使用されず、クラス変数が使用されていることがわかります。
理解を深めるために、両方のケースで上記のコードを実行することをお勧めします。
要素のバインド
標準のデータソースではなく、ページ上の別の要素にバインドすることもできます。 SliderとRectangleが作成され、スライダーを使用して長方形の幅と高さがバインドされる 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>
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
以下に示すように、スライダーを使用して、長方形のサイズを変更できます。
Windows 10開発-XAMLパフォーマンス
起動時のアプリケーションの表示速度や、次のコンテンツを表示するためにナビゲートする速度など、アプリケーションのパフォーマンス。 はとても重要です。
アプリケーションのパフォーマンスは、アプリケーション内にあるすべてのXAMLコードを解析するXAMLレンダリングエンジンの機能など、多くの影響を受けます。 XAMLはUIを作成するための非常に強力なツールですが、Windows 10アプリケーションで利用できるようになった新しい手法を使用すると、より堅牢になります。
たとえば、アプリケーションには特定のものがあり、ページが読み込まれたときに表示したいが、後で必要にならないものがあります。 また、起動時にすべてのUI要素をロードする必要がない場合もあります。
Windows 10アプリでは、XAMLにいくつかの新機能が追加され、XAMLのパフォーマンスが向上しました。
ユニバーサルWindowsアプリケーションのパフォーマンスは、次の手法によって改善できます。
- プログレッシブレンダリング
- 遅延読み込み
プログレッシブレンダリング
Windows 10では、2つの新しい非常に優れた機能がXAMLに導入されています。 彼らは-
x:バインド
これは、バインディングに使用されるXAMLで導入された新しい構文で、 Binding 構文とほぼ同じように機能します。 x:Bind には2つの重要な違いがあります。コンパイル時の構文検証とパフォーマンスの向上を提供します。
X:フェーズ
データテンプレート内のXAMLコントロールのレンダリングを優先する機能を提供します。 各UI要素には、1つのフェーズのみを指定できます。 その場合、それは要素のすべてのバインディングに適用されます。 フェーズが指定されていない場合、フェーズ0が想定されます。
ユニバーサルWindowsプラットフォーム(UWP)アプリケーションでは、これら2つの新機能によりパフォーマンスが向上します。 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;
}
}
}
上記のコードが実行されると、次のウィンドウが表示されます。
*X:Phase* と *x:Bind* を使用して、 *ListView* および *GridView* アイテムをインクリメンタルにレンダリングし、パン操作を改善します。
遅延読み込み
遅延読み込みは、アプリケーションの起動時にXAML UI要素の数を減らすことで起動読み込み時間を最小限に抑えるために使用できる手法です。 アプリケーションに30個のUI要素が含まれていて、ユーザーが起動時にこれらすべての要素を必要としない場合、必要のないすべての要素は、延期することでロード時間を節約できます。
*x:DeferLoadStrategy = "Lazy"* は、要素とその子の作成を遅らせます。これにより、起動時間が短縮されますが、メモリ使用量がわずかに増加します。
遅延要素は、要素で定義された名前で FindName を呼び出すことで実現/作成できます。
遅延要素が作成されると、いくつかのことが起こります-
- 要素のLoadedイベントが発生します。
- 要素上のすべてのバインディングが評価されます。
- 遅延要素を含むプロパティのプロパティ変更通知を受信するようにアプリケーションが登録されている場合、通知が発生します。
以下に、4つのテキストブロックを含むグリッドに 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 は起動時にロードされません。
[*要素の表示]ボタンをクリックすると、テキストブロックが読み込まれ、アプリケーションの起動パフォーマンスが向上します。
Windows 10開発-アダプティブデザイン
Windows 10では、ユニバーサルWindowsプラットフォーム(UWP)アプリケーションは次のような多くのデバイスファミリで実行されます-
- デスクトップデバイスファミリ-タブレット、ラップトップ、PC
- モバイルデバイスファミリ-Windows Phone、ファブレット
- * IoTデバイスファミリ*-ウェアラブルや家電などのコンパクトなデバイス
- チームデバイスファミリ-Surfaceハブ
各デバイスファミリには、独自の画面サイズとウィンドウサイズがあります。 では、画面サイズと入力方法が劇的に異なる複数のデバイスで優れたユーザーエクスペリエンスを提供するアプリをどのように設計するのでしょうか。
複数のデバイスファミリ用にアプリケーションを設計するには、追加の検討、計画、および設計が必要です。 Windows 10 UWPは、一連の組み込み機能とユニバーサルビルディングブロックを提供します。これにより、複数のデバイス向けの設計が容易になり、プラットフォームコントロールでサポートされるさまざまな画面サイズとウィンドウサイズに自動的にスケーリングできます。
新しい組み込み機能
以下は、開発者がUWPアプリケーションを作成するときに使用できる新機能です。 これらの機能は自動で無料です。
効果的なピクセルとプラットフォームのスケーリング
UWPアプリケーションがWindows 10でサポートされているデバイスで実行されている場合-
- システムは、アルゴリズムを使用して、コントロール、フォント、およびその他のUI要素が現在実行されているデバイスの画面に表示される方法を正規化します。
- スケーリングアルゴリズム。表示距離と画面密度(1インチあたりのピクセル数)を制御して、想定サイズ(物理サイズではなく)を最適化します。
- スケーリングアルゴリズムにより、10フィート離れたSurface Hubの36ピクセルフォントは、数インチ離れた5インチ電話の36ピクセルフォントと同じくらいユーザーに読みやすくなります。
ユニバーサル入力とスマートな相互作用
ユニバーサルWindowsプラットフォームには、すべてのデバイスの入力を理解する組み込みのスマートインタラクション入力システムがあります。 たとえば、アプリケーションでクリックインタラクションを設計する場合、クリックが実際のマウスクリックによるものか、指のタップによるものかを知る必要はありません。 システムが自動的に実行します。
ユニバーサルビルディングブロック
いくつかの貴重なビルディングブロックがあり、ユニバーサルWindowsプラットフォーム(UWP)で複数のデバイスファミリ用のアプリケーションを簡単に設計できます。
ユニバーサルコントロール
UWPは、すべてのWindows 10デバイスで正常に動作することが保証されているユニバーサルコントロールのセットを提供します。
- この「ユニバーサルコントロール」リストには、ラジオボタン、コンボボックス、テキストボックスなどの一般的なコントロールが含まれています。
- また、データのストリームとテンプレートからアイテムのリストを生成できる grid view や list view などの高度なコントロールも含まれています。
ユニバーサルスタイル
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アプリケーションでレスポンシブデザインを実装できる2つの新しいメカニズムがあります。 新しい 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以上の場合、方向は水平になります。そうでない場合、垂直のままになります。 上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。このウィンドウには、垂直方向に3つのテキストブロックが含まれています。
上記のウィンドウの幅を変更すると、次のウィンドウが表示されます-
これで、テキストブロックが水平方向に並んでいることがわかります。
相対パネル
*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>
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
上記のウィンドウのサイズを変更すると、下に示すように、緑色の長方形が青色の長方形の左側の一番上の行で調整されていることがわかります。
Windows 10開発-アダプティブコード
この章では、Windows 10でサポートされるさまざまなデバイスへのアプリケーションの採用について説明します。 UIと、UWPアプリケーションで使用されるすべてのトリック、テクニック、およびコントロールの採用については、既に学習しました。
次に、コードの採用について学習します。なぜなら、
- アプリケーションコードはすべてのデバイスで同じではありません。
- 特にXboxで使用されるAPIは、モバイルデバイスでは使用できません。 同じことがHoloLensなどにも当てはまります。
*Adaptive* コードは、アプリケーションを条件付きで点灯させ、特定のデバイスファミリおよび/またはプラットフォーム/拡張APIの特定のバージョンで実行している場合にのみコードを実行できます。
コードを書く
Windows 10では、C ++、C#、Visual Basic、またはJavaScriptを使用して、Visual StudioでUWPアプリケーションを実装できます。
- C#とVisual Basicを使用すると、UI設計にXAMLを使用できます。
- C ++では、XAMLを使用する代わりにDirectXを使用できます。
- JavaScriptの場合、クロスプラットフォームWeb標準であるプレゼンテーションレイヤーにHTMLを使用できます。
Windows Core APIは、コードとUIに必要なほとんどの機能を含むすべてのデバイスに対して同じ方法で実行されます。 ただし、特定のデバイスファミリに合わせて調整されたコードとUIの場合は、適応コードと適応UIを使用する必要があります。
ターゲットデバイスファミリによって実装されていないAPIの呼び出し-
UIはさまざまな画面に簡単に適応しますが、さまざまなデバイスファミリにはさまざまな画面サイズがあるだけでなく、それ以上の機能があります。
- たとえば、携帯電話にはBackやCameraなどのハードウェアボタンがありますが、PCなどの他のデバイスでは使用できない場合があります。
- 既定では、コアAPIにはほとんどの機能が含まれており、すべてのデバイスで機能しますが、外部アセンブリと同様にUWPアプリケーションで拡張SDKを参照することでデバイス固有の機能を使用できます。
アプリケーションに必要な特定の拡張SDKを追加するには、以下の手順に従ってください-
*[参照]* を右クリックします。
* *「参照の追加...」*を選択します。 次のダイアログが開きます。
- 拡張機能の追加は、プロジェクト参照を追加するのと同じくらい簡単です。
- これで、リストから任意の拡張SDKを追加できます。これには、デスクトップ拡張、IoT拡張、モバイル拡張などが含まれます。
デスクトップとモバイルの拡張機能は、最も一般的な2つのプラットフォーム拡張機能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;
}
電話カメラボタンコードは、デバイスでMobile Extension SDKが有効になっている場合にのみ実行されます。 同様に、以下に示すように、 IsTypePresent の代わりに IsEventPresent 、 IsMethodPresent 、 IsPropertyPresent を使用して、現在のAPIバージョンの特定のイベント、メソッド、またはプロパティを確認することもできます。
bool isHardwareButtons_CameraPressedAPIPresent =
Windows.Foundation.Metadata.ApiInformation.IsEventPresent
("Windows.Phone.UI.Input.HardwareButtons", "CameraPressed");
UWPのWin32 API
C ++/CXで記述されたUniversal Widows Platform(UWP)アプリケーションまたはWindowsランタイムコンポーネントは、現在UWPの一部でもあるWin32 APIにアクセスできます。 すべてのWindows 10デバイスファミリは、アプリケーションを Windowsapp.lib とリンクすることにより、Win32 APIを実装できます。
*Windowsapp.lib* は、UWP APIのエクスポートを提供する「傘」ライブラリです。 *Windowsapp.lib* にリンクすると、すべてのWindows 10デバイスファミリに存在する *dlls* へのアプリの依存関係が追加されます。
アプリケーションがデスクトップと電話の両方をターゲットとする簡単な例を見てみましょう。 したがって、アプリケーションをデスクトップで実行すると、ステータスバーは表示されませんが、同じアプリケーションを電話で実行すると、ステータスバーが表示されます。
以下に、さまざまなコントロールが追加された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 Status Barチェックボックス
Windows10開発-ファイル管理
どのアプリケーションでも、最も重要なことの1つはデータです。 .net 開発者であれば、分離ストレージについて知っているかもしれません。ユニバーサルWindowsプラットフォーム(UWP)アプリケーションでも同じ概念が続きます。
ファイルの場所
これらは、アプリケーションがデータにアクセスできる領域です。 アプリケーションには特定のアプリケーション専用の領域があり、他のアプリケーションにはアクセスできませんが、ファイル内にデータを保存および保存できる領域は他にもたくさんあります。
以下に、各フォルダーの簡単な説明を示します。
S.No. | Folder & Description |
---|---|
1 |
App package folder パッケージマネージャーは、アプリのすべての関連ファイルをアプリパッケージフォルダーにインストールします。アプリはこのフォルダーからのみデータを読み取ることができます。 |
2 |
Local folder アプリケーションは、ローカルデータをローカルフォルダーに保存します。 ストレージデバイスに制限までデータを保存できます。 |
3 |
Roaming folder アプリケーションに関連する設定とプロパティは、ローミングフォルダーに保存されます。 他のデバイスもこのフォルダーのデータにアクセスできます。 アプリケーションごとに最大100KBのサイズに制限されています。 |
4 |
Temp Folder 一時記憶域の使用。アプリケーションを再度実行したときに一時記憶域が引き続き使用できるという保証はありません。 |
5 |
Publisher Share 同じ発行元のすべてのアプリの共有ストレージ。 アプリマニフェストで宣言されています。 |
6 |
Credential Locker パスワード資格情報オブジェクトの安全な保管に使用されます。 |
7 |
OneDrive OneDriveは、Microsoftアカウントに付属する無料のオンラインストレージです。 |
8 |
Cloud データをクラウドに保存します。 |
9 |
Known folders これらのフォルダーは、マイピクチャ、ビデオ、音楽などの既知のフォルダーです。 |
10 |
Removable storage USBストレージデバイスまたは外付けハードドライブなど |
ファイル処理API
Windows 8では、ファイル処理用の新しいAPIが導入されました。 これらのAPIは、 Windows.Storage および Windows.Storage.Streams 名前空間にあります。 System.IO.IsolatedStorage 名前空間の代わりにこれらのAPIを使用できます。 これらの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;
}
}
}
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
ここで、テキストボックスに何かを書いて、*「データをファイルに書き込む」*ボタンをクリックします。 プログラムは、データをローカルフォルダーのテキストファイルに書き込みます。 *「ファイルからデータを読み取る」*ボタンをクリックすると、プログラムは同じテキストファイルからデータを読み取ります。このファイルはローカルフォルダーにあり、テキストブロックに表示されます。
Windows 10開発-SQLiteデータベース
多くのアプリケーションには、特定の種類のデータがあり、それらは互いに何らかの関係があります。 ファイルに保存するのが難しいこれらのタイプのデータは、データベースに保存できます。
アプリケーションのSQLサーバーやOracleデータベースなど、データベースの種類に精通している場合は、* SQLiteデータベース*を非常に簡単に理解できます。
SQLiteとは何ですか?
SQLiteは、自己完結型、サーバーレス、ゼロ構成、トランザクションSQLデータベースエンジンを実装するソフトウェアライブラリです。
重要な機能は-
- SQLiteは、世界で最も広く展開されているデータベースエンジンです。
- SQLiteのソースコードはオープンソースです。
- 携帯性とフットプリントが小さいため、ゲームおよびモバイルアプリケーションの開発に大きな影響を与えました。
SQLiteの利点
以下はSQLiteの利点です-
- これは非常に軽量なデータベースです。
- プラットフォームに依存せず、すべてのプラットフォームで動作します。
- メモリフットプリントが小さい。
- 信頼できます。
- セットアップやインストールの必要はありません。
- 依存関係はありません。
ユニバーサルWindowsプラットフォーム(UWP)アプリケーションで SQLite を使用するには、以下の手順に従う必要があります。
- UWPSQLiteDemo という名前の新しいユニバーサルWindows空アプリを作成します。
- [ツール]メニューに移動し、[拡張機能と更新プログラム]を選択します。 次のダイアログが開きます。
- 拡張機能と更新プログラムを選択すると、次のウィンドウが開きます。
- ここで、 Online オプションを選択し、左ペインからSQLiteを検索します。
- Universal App Platform用のSQLiteをダウンロードしてインストールします。
- 次に、[ツール]メニューに再度移動し、以下に示すように[* NuGetパッケージマネージャー]> [パッケージマネージャーコンソール]メニューオプションを選択します。
- パッケージマネージャーコンソールで次のコマンドを記述し、Enterキーを押してこのコマンドを実行します-
Install-Package SQLite.Net-PCL
- ソリューションエクスプローラーで[参照]を右クリックし、[参照の追加]を選択します。
- 次のダイアログが開きます。
- 左ウィンドウ枠の[ Universal Windows ]から[ Extensions ]を選択し、中央のウィンドウで[SQLite for Universal App Platform]をオンにして、[OK]をクリックします。
- これで、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; }
}
}
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
- 名前*と*年齢*を入力し、*追加*ボタンをクリックします。
ここで、 Retrieve ボタンをクリックします。 *テキストブロック*に次のデータが表示されます。
IDフィールドは、Customerクラスで指定される主キーおよび自動インクリメントフィールドです。
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
Windows10 Dev-アプリ通信
アプリ間通信とは、同じデバイスにインストールされている別のアプリケーションとアプリケーションが通信できることを意味します。 これは、ユニバーサルWindowsプラットフォーム(UWP)アプリケーションの新機能ではなく、Windows 8.1でも利用可能でした。
Windows 10では、同じデバイス上のアプリケーション間で簡単に通信できるように、いくつかの新しい改良された方法が導入されています。 2つのアプリ間の通信は、次の方法で行うことができます-
- あるアプリケーションがいくつかのデータで別のアプリを起動します。
- アプリは、何も起動せずにデータを交換するだけです。
アプリからアプリへの通信の主な利点は、アプリケーションを小さなチャンクに分割できることです。これを簡単に維持、更新、使用できます。
アプリを準備する
以下の手順に従うと、他のアプリケーションがアプリケーションを起動できます。
- アプリケーションパッケージマニフェストにプロトコル宣言を追加します。
- Package.appxmanifest ファイルをダブルクリックします。このファイルは、次に示すようにソリューションエクスプローラーで使用できます。
- *宣言*タブに移動し、以下に示すようにプロトコルの名前を書きます。
- 次のステップは、*アクティベーション*コードを追加することです。これにより、アプリは他のアプリケーションによって起動されたときに適切に応答できます。
- プロトコルのアクティベーションに応答するには、アクティベーションクラスの 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"));
*ProtocolHandlerDemo* と *FirstProtocolHandler* を備えた2つのUWPアプリケーションがある簡単な例でこれを理解しましょう。
この例では、 ProtocolHandlerDemo アプリケーションにはボタンが1つ含まれており、ボタンをクリックすると、 FirstProtocolHandler アプリケーションが開きます。
1つのボタンを含む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>
*OnActicated* がオーバーライドされた *App.xaml.cs* ファイルのC#実装を以下に示します。 *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 アプリケーションをコンパイルして実行すると、次のウィンドウが表示されます。
これで、ボタンをクリックすると、以下に示すように FirstProtocolHandler アプリケーションが開きます。
Windows 10開発-ローカリゼーション
Windowsは世界中のさまざまな市場で、文化、地域、または言語が異なる対象ユーザーに使用されています。 ローカリゼーションとは、アプリケーションがサポートする特定のカルチャに合わせて、アプリケーションリソースをローカライズバージョンに翻訳することです。
1つの言語のみでアプリケーションを開発することは、ビジネスと顧客を制限していることを意味します。 顧客ベースを増やしてビジネスを拡大したい場合は、アプリケーションがグローバルに利用可能で到達可能でなければなりません。 製品の費用対効果の高いローカリゼーションは、より多くの顧客にリーチするための最良かつ最も経済的な方法の1つです。
Windows 10では、ローカライズ可能なアプリケーションは resx ファイルを使用して非常に簡単に作成できます。これは、ローカライズの最も簡単なソリューションです。
以下のすべての手順に従うことにより、簡単な例を使用してこれを理解しましょう。
UIリソースの翻訳
コードまたはマークアップに直接配置する代わりに、UIの文字列リソースをリソース( resw )ファイルに配置し、コードまたはマークアップからこれらの文字列を参照できます。 以下の手順に従って、リソースファイルに文字列を追加します。
- 新しいユニバーサルWindowsプラットフォーム(UWP)アプリケーションを作成します。
- *ソリューションエクスプローラー*で、プロジェクトを右クリックし、*追加>新しいフォルダー*を選択します。
- 新しいフォルダの名前を "Strings" に変更します。
- Strings フォルダーを右クリックし、「 en-US 」という名前の新しいフォルダーを追加します。 これらは言語および国/地域名に固有の命名規則であり、各国語サポート(NLS)APIリファレンスhttps://msdn.microsoft.com/en-us/goglobal/bb896001.aspx[msdn。 microsoft.com]ページ。
- en-US フォルダーを右クリックし、追加>新規アイテム…を選択します。
- 次のダイアログが開きます。
- *「リソースファイル(.resw)」*を選択し、[追加]ボタンをクリックします。
- 次に、XAMLファイルに移動して、以下に示すように、いくつかのプロパティを持つハブコントロールを追加します。
<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" は、ローカライズに使用される識別子です
- さて、上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
ヘッダー、前景、背景色など、ハブに関連するすべての情報はXAMLで設定されます。
- 次に示すように、 Strings/en-US フォルダーの Resource.resw ファイルに情報の一部を追加します。
- ローカライズされたテキストを必要とするすべてのコントロールを。 resw ファイルに関連付ける必要があります。 これを行うには、このようなXAML要素で x:Uid 属性を使用します-
- x:Uid = "HubControl" は、 resw ファイルで使用され、ヘッダー、前景色、および背景色に文字列を割り当てます。
- これで、エミュレータでアプリケーションをコンパイルして実行すると、次のウィンドウが表示されます。 ヘッダー、前景色、および背景色の値が Resources.resw ファイルから選択されていることがわかります。
- フランス語、ドイツ語、日本語など、他の言語用に他の Resource.resw ファイルを追加できます。 English-USで行ったように手動で行いますが、Microsoftは Resource.resw を他の言語に簡単に翻訳できる Multilingual App Toolkit を提供しています。
- [ツール]> [拡張機能]および[更新]メニューに移動し、[多言語アプリ]ツールキットを検索します。
- このツールキットをダウンロードしてインストールします。 インストールが完了したら、Visual Studioを再起動して同じプロジェクトを開きます。
- 次に、[ツール]> [多言語アプリ]ツールキットメニューオプションからこのツールキットを有効にします。
- これで、他の言語の翻訳を追加できます。
- Solution Explorer でプロジェクトを右クリックし、メニューから Multilingual App Toolkit> Add Translation Languagesオプションを選択します。
- 次の*翻訳言語*ダイアログが開きます。 必要な言語を選択して、それらの文化に合わせてアプリケーションをローカライズできます。
- ドイツ語*言語を選択して、 *OK ボタンをクリックします。
- また、 Resources.resw ファイルが Strings \ de フォルダー内に作成されていることもわかります。
- これで、*。xlf *ファイル内に別の *MultiLingualResources が追加されていることがわかります。 このファイルをダブルクリックすると、 Multilingual エディターが開き、翻訳された文字列を確認および検証し、必要に応じて変更を加えます。
- 変更を行い、背景色が茶色に変更され、ヘッダーテキストがドイツ語に適切に翻訳されているかどうかを確認します。
- 上記の例のように、ハブの背景色は青色から茶色に変わり、前景色は同じままです。
- ここで、 Strings \ de フォルダー内にある Resources.resw を開きます。
- 多言語エディタの前景色を変更していないため、ここでは2つの文字列のみが言及されていることがわかります。
アプリケーションのローカライズバージョンを確認するには、マシンのカルチャを変更します。 マシンの文化を変更するには、以下の手順に従ってください。
- PC設定に移動して、[時間と言語]を選択します。
- 左側のペインから*地域と言語*を選択し、*言語の追加*をクリックします。
- 上記のように*ドイツ語*言語を選択すると、別のダイアログが開きます。
- *ドイツ語(ドイツ)*を選択して、このダイアログボックスを閉じます。
- Deutschをデフォルト言語にします。
- アプリケーションを実行すると、次のウィンドウが表示されます。
- これで、アプリケーションの出力をドイツ語で見ることができます。
Windows 10開発-ライフサイクル
歴史的に、Windowsには、ユーザーが複数のアプリケーションを同時に実行できる環境があります。 ユーザーは異なるアプリケーションを簡単に切り替えることができます。 このモデルは、使用が通常単一のアプリケーションに集中している電話またはタブレットデバイスではうまく機能しません。
Windows 8ストアアプリケーションプログラマが直面する最も重要な課題の1つは、アプリケーションのライフサイクルの管理と理解です。 Windows Phoneアプリケーションを構築している場合、その多くはおなじみでしょう。
- Windows 8では、オペレーティングシステムがアプリケーションのライフタイムを管理し、ユーザーはアプリケーションを終了できますが、通常、ユーザーは実行中のアプリケーションを意識的に終了することなく新しいアプリケーションを開きます。
- Windows 10用のユニバーサルWindowsプラットフォーム(UWP)はこれらの問題に対処し、デスクトップユーザーにいくつかの素晴らしい機能を提供し、複数のウィンドウエクスペリエンスで複数のアプリケーションを実行できるようにします。
Windowsアプリケーションは、以下に示すように、基本レベルで3つの状態で存在できます。
- ランニング
- 停止中
- 終了
- ユーザーがアプリケーションを起動/アクティブ化すると、アプリケーションは「実行中」状態になります。
- ユーザーが使用せず、フォアグラウンドになくなった場合、アプリケーションを中断できます。
- アプリケーションは、サスペンド状態からそのアプリケーションを再開するか、OSを終了してシステムリソースを再利用できます。
プロセス状態遷移
実行中のアプリケーションのプロセス状態の遷移を理解することが重要です。 ユーザーが最初にアプリケーションを起動すると、スプラッシュ画面が表示され、アプリケーションの実行が開始されます。
プロセスは次のように説明することができます-
- アプリケーションが中断している場合、アプリケーションはその中断されたイベントを処理するために5秒かかります。
- アプリケーションが中断されると、コードは絶対に実行されず、リソースも割り当てられません。
- 再開すると、アプリは再開したことが通知されます。 中断状態から来ている場合は、何もする必要はありません。
- メモリ不足の状態では、アプリケーションが終了する可能性があります。
- その時点では通知されないため、保存を行う場合は、アプリケーションの一時停止状態になったときに行う必要があることに注意してください。
アプリケーションが Running 状態と Suspended 状態の間を行き来するとき、それぞれ中断および再開イベントを発生させます。
場合によっては、データを保存する必要があります。 次に、以下に示すように非同期メソッドを呼び出す必要があります。
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#コードを示します。 現在のデータは、ローカル設定の* suspendイベント*に保存され、次に示すように、ローカル設定の* resumeイベント*で取得されます。
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);
}
}
}
}
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。 次に、必要な情報を書き込みます。
- ライフサイクル*イベントドロップダウンメニューに移動して、*中断*を選択します。 これで、アプリケーションが中断され、必要な情報がローカル設定に保存されます。 以下のスクリーンショットをご覧ください。
ここで、アプリケーションを再開する場合、 Lifecycle Events メニューから Resume オプションを選択します。
これで、保存された情報がローカル設定から取得され、アプリケーションが中断されたのと同じ状態で再開されることがわかります。
Windows10 Dev-バックグラウンド実行
ユニバーサルWindowsプラットフォーム(UWP)には、アプリケーションがフォアグラウンドで実行されていないときにアプリケーションがいくつかの機能を実行できるようにする新しいメカニズムが導入されています。 UWPは、 Background Tasks and Triggers のバックグラウンドで実行時間を延長するアプリケーションの機能も向上させます。 バックグラウンド実行は、アプリケーションのライフサイクルを補完する真のテールです。
バックグラウンドタスクの重要な機能は次のとおりです-
- バックグラウンドタスクは、システムまたはタイムイベントによってトリガーされ、1つ以上の条件によって制約される可能性があります。
- バックグラウンドタスクがトリガーされると、関連するハンドラーが実行され、バックグラウンドタスクの作業を実行します。
- バックグラウンドタスクは、バックグラウンドタスクを登録したアプリが中断されている場合でも実行できます。
- これらは標準のアプリケーションプラットフォームの一部であり、基本的にアプリにシステムイベント(トリガー)に登録する機能を提供します。 そのイベントが発生すると、バックグラウンドで事前定義されたコードブロックが実行されます。 システムトリガーには、ネットワーク接続の変更やシステムタイムゾーンなどのイベントが含まれます。
- バックグラウンド実行は保証されていないため、重要な機能や機能には適していません。 *OSには、同時に実行できるバックグラウンドタスクの数に制限があります。 そのため、トリガーが起動されて条件が満たされた場合でも、タスクは実行できません。
バックグラウンドタスクの作成と登録
バックグラウンドタスククラスを作成し、アプリがフォアグラウンドにないときに実行するように登録します。* 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ファイルにボタンを1つ追加します。
<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 という名前を付けます。
*以下に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 プロジェクトを追加します。
- 次に、 UWPBackgroundDemo プロジェクトの Package.appxmanifest ファイルに移動し、[宣言]タブに次の情報を追加します。
- 最初にバックグラウンドスタッフプロジェクトをビルドしてから、 UWPBackgroundDemo プロジェクトをビルドして実行します。
- 上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
- *ボタン*をクリックすると、バックグラウンドタスクが実行され、ウィンドウの右端に通知が表示されます。
Windows 10開発-サービス
この章では、UWPアプリが他のユニバーサルWindowsプラットフォーム(UWP)アプリケーションにサービスを提供または提供する方法について学習します。 実際、この章は Background execution の章の拡張であり、特別な場合です。
- Windows 10では、アプリサービスは、アプリが他のアプリにサービスを提供する方法またはメカニズムです。
- アプリサービスはバックグラウンドタスクの形式で機能します。
- フォアグラウンドアプリは、別のアプリのアプリサービスを呼び出して、バックグラウンドでタスクを実行できます。
アプリサービスはWebサービスに似ていますが、アプリサービスはWindows 10デバイスで使用されます。
ユニバーサルWindowsプラットフォーム(UWP)アプリケーションは、さまざまな方法で別のUWPアプリケーションと対話できます-
- LaunchUriAsyncを使用したURIの関連付け
- LaunchFileAsyncを使用したファイルの関連付け
- LaunchUriForResultsAsyncを使用した結果の起動
- アプリサービス
最初の3つの方法は、両方のアプリケーションがフォアグラウンドである場合に使用されますが、Appサービスは*バックグラウンドタスク*で使用され、その場合、クライアントアプリケーションはフォアグラウンドにあり、Appサービスを使用できる必要があります。
アプリサービスは、非ビジュアルサービスが提供されるアプリケーションで非常に有益です。 フォアグラウンドアプリが画像を取得し、それらのバイトをアプリサービスに送信してバーコードを識別するバーコードスキャナー。
これらすべての概念を理解するために、Microsoft Visual Studio 2015で AppServiceProvider という名前の新しいUWPプロジェクトを作成しましょう。
*Package.appmenifest* ファイルに、次の情報を追加します。
フォアグラウンドアプリケーションによって呼び出すことができるアプリサービスを作成するには、アプリサービスがバックグラウンドタスクとして実装されているため、新しい* Windowsランタイム*コンポーネントプロジェクトを MyAppService という名前でソリューションに追加します。
*AppServiceProvider* プロジェクトに *MyAppService* プロジェクトへの参照を追加します。
*MyAppService* プロジェクトから *class1.cs* ファイルを削除し、インベントリ名を持つ新しいクラスを追加します。これにより、 *IBackgrounTask* インターフェイスが実装されます。
*IBackgrounTask* インターフェースには、バックグラウンドタスク用に実装する必要がある*「Run」*メソッドが1つしかありません。
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();
}
}
}
}
新しい空のUWPプロジェクト ClientApp を追加してクライアントアプリを作成し、XAMLファイルに次のように1つのボタン、1つのテキストボックス、2つのテキストブロックを追加します。
<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>
以下に、Appサービスが要求されるボタンクリックイベントの実装を示します。
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 プロジェクトをスタートアッププロジェクトに設定し、 Build> Deploy Solutionからこのソリューションを展開する必要があります。
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。 Appサービスでは、2つのアイテムの情報を追加しました。 したがって、0または1を入力して、これらのアイテムの情報を取得できます。
0を入力してボタンをクリックすると、バックグラウンドタスクとしてAppサービスが実行され、 textblock にアイテム情報が表示されます。
Windows 10開発-Webプラットフォーム
Windows 10では、開発者がユニバーサルWindowsプラットフォーム(UWP)アプリケーションを作成し、そのアプリケーションでWebサイトをホストし、ダウンロードするためにWindowsストアに公開することが非常に簡単です。
利点
- Windows 10のこの新機能により、Web開発者はWebサイトのコンポーネントをWindowsアプリに簡単に変換できます。
- ただし、これらのコンポーネントはすべて、独自のWebサーバーでリモートでホストされます。
- さらに、ユニバーサルAPIにアクセスすることもできます。これにより、開発者は通知、カメラ、カレンダー、Cortanaなどのクールなものにアクセスできます。
マイクロソフトは、この機能と機能により、より多くの開発者がWindows 10プラットフォーム用のアプリを作成できるようになることを期待しています。
- デスクトップ
- スマートフォン
- Xbox
- 錠剤
- HoloLensおよびその他のデバイス
現在、この機能には問題が1つしかなく、それがセキュリティです。 明らかに、マイクロソフトはできるだけ早くこれに対処する必要があります。
Webサイトをホストし、そのWebサイトをWindowsアプリに変換する例の助けを借りて理解しましょう。
以下の手順に従ってください。
- File> New> Project から新しいユニバーサルWindowsプロジェクトを作成します。
- [新しいプロジェクトとダイアログ]の左ペインから[JavaScript]> [Windows]> [ユニバーサル]オプションを選択します。
- 中央のペインから、* Blank App(Universal Windows)*を選択します。
- 名前フィールド UWPWebApp に書き込み、 OK ボタンをクリックします。
- [ソリューションエクスプローラー]ウィンドウを見ると、いくつかのファイルとフォルダーが表示されます。
- css、js、WinJS フォルダー、および defaultl ファイルを削除します。この例では、Webサイトをホストしているだけであり、すべてのコンテンツがリモートサーバー上にあると想定しているためです。 したがって、ほとんどのローカルファイルは必要ありません。
- 上記のファイルとフォルダーを削除した後、 package.appxmanifest ファイルをダブルクリックすると、次のウィンドウが表示されます。
- 次に、[開始ページ]フィールドの defaultl をURLに置き換えて、WebサイトのURLを指定します。 デモンストレーションの目的で、URL * https://www.google.com.pk/* Webサイトを使用します。
- [コンテンツURI] タブに移動して、Webアプリのルールとアクセス許可を定義します。
- [URI]フィールドで、Webサイトリンクを指定し、[* Rule]ドロップダウン*から[ Include ]、 WinRT Access から All を選択します。
- このアプリケーションを実行すると、以下に示すように、アプリにGoogleスタートページが表示されます。
Windows10 Dev-コネクテッドエクスペリエンス
既に知っているように、Windows 10では、複数のWindows 10デバイスで実行および実行できるアプリケーションを作成できます。 これらの異なるデバイスがあり、異なるデバイスで実行されているにもかかわらず、1つのアプリケーションのように感じさせたいとします。
ユニバーサルWindowsプラットフォーム(UWP)では、すべてのWindows 10デバイスで単一のアプリケーションを実行でき、ユーザーにそれが1つのアプリケーションであるという感覚を与えることができます。 これは「接続エクスペリエンス」として知られています。
コネクテッドエクスペリエンスの重要な機能-
- Windows 10は、よりパーソナルコンピューティングの時代への第一歩であり、アプリ、サービス、およびコンテンツをデバイス間でシームレスかつ簡単に移動できます。
- 接続されたエクスペリエンスを使用すると、そのアプリケーションに関連するデータと個人設定を簡単に共有でき、すべてのデバイスで利用できるようになります。
この章では、学習します-
- これらの共有データまたは設定は、その1つのアプリケーションのデバイスで使用できるように保存されます。
- ユーザーの識別方法。異なるデバイスで同じアプリケーションを使用しているのは同じユーザーであること。
Windows 10は大胆な一歩を踏み出しました。 あなたがMicrosoftアカウント(MSA)またはあなたの企業または(仕事)アカウントのいずれかでWindows 10にログインすると、それが仮定されます-
- OneDrive for MSAアカウントに無料でアクセスでき、エンタープライズアカウントのクラウドバージョンであるActive Directory(AD)およびAzure Active Directory(AAD)にアクセスできます。
- さまざまなアプリケーションとリソースにアクセスできます。
- デバイスとアプリケーションはローミング状態と設定になっています。
Windows 10でのローミング
PCにログオンするとき、ロック画面や背景色などの設定をしたり、さまざまな種類の設定をカスタマイズしたりします。 Windows 10で実行されているコンピューターまたはデバイスが複数ある場合、同じアカウントで他のデバイスにログインすると、1つのデバイスの設定と設定がクラウドから同期されます。
Windows 10では、アプリケーション設定を設定またはパーソナライズすると、これらの設定はUWPで利用可能なローミングAPIを使用してローミングされます。 同じアプリケーションを他のデバイスで再度実行すると、最初に設定が取得され、そのデバイスのアプリケーションにそれらの設定が適用されます。
ローミングデータをクラウドにアップロードするには、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();
}
}
}
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
背景色としてグレー色を選択し、このアプリを閉じましょう。
このデバイスまたは他のデバイスでこのアプリを実行すると、背景色がグレーに変更されていることがわかります。 これは、アプリが RoamingSettings で背景色の変更情報を正常に取得したことを示しています。
Windows 10開発-ナビゲーション
ユニバーサルWindowsプラットフォーム(UWP)アプリケーションでは、ナビゲーションは、ナビゲーション構造、ナビゲーション要素、およびシステムレベルの機能の柔軟なモデルです。 アプリ、ページ、コンテンツ間を移動するためのさまざまな直感的なユーザーエクスペリエンスを可能にします。
すべてのコンテンツと機能が1つのページに簡単に収まり、開発者が複数のページを作成する必要がない状況とシナリオがあります。 ただし、ほとんどのアプリケーションでは、異なるコンテンツと機能間の相互作用に複数のページが使用されます。
アプリに複数のページがある場合、開発者が適切なナビゲーションエクスペリエンスを提供することが非常に重要です。
ページモデル
通常、ユニバーサルWindowsプラットフォーム(UWP)アプリケーションでは、単一ページナビゲーションモデルが使用されます。
重要な機能は-
- 単一ページナビゲーションモデルは、アプリケーションのすべてのコンテキストと追加コンテンツおよびデータを中央フレームに保持します。
- アプリケーションのコンテンツを複数のページに分割できます。 ただし、あるページから別のページに移動すると、アプリケーションはページをメインページフォームにロードします。
- アプリケーションのメインページもコードとデータもアンロードされないため、状態の管理が容易になり、ページ間の遷移アニメーションがよりスムーズになります。
マルチページナビゲーションは、アプリケーションのコンテキストを気にすることなく、異なるページまたは画面間を移動するためにも使用されます。 複数ページのナビゲーションでは、各ページに独自の機能セット、ユーザーインターフェイス、データなどがあります。
通常、マルチページナビゲーションは、Webサイト内のWebページで使用されます。
ナビゲーション構造
複数ページのナビゲーションでは、各ページに独自の機能セット、ユーザーインターフェイス、データなどがあります。 たとえば、写真アプリケーションには写真をキャプチャするための1つのページがあり、ユーザーが写真を編集したい場合は別のページに移動し、画像ライブラリを維持するために別のページがあります。
アプリケーションのナビゲーション構造は、これらのページの編成方法によって定義されます。
以下は、アプリケーションでナビゲーションを構造化する方法です-
階層
このタイプのナビゲーション構造では、
- ページは、構造のようなツリーに編成されます。
- 各子ページには1つの親しかありませんが、親は1つ以上の子ページを持つことができます。
- 子ページに到達するには、親を経由する必要があります。
Peer
このタイプのナビゲーションでは-
- ページは並んで存在します。
- 1つのページから別のページに任意の順序で移動できます。
ほとんどのマルチページアプリケーションでは、両方の構造が同時に使用されます。 一部のページはピアとして編成され、一部は階層に編成されています。
3つのページを含む例を見てみましょう。
- UWPNavigation という名前の空のUWPアプリケーションを作成します。
- *ソリューションエクスプローラー*でプロジェクトを右クリックして、さらに2つの空白ページを追加し、メニューから*追加>新規アイテム*オプションを選択すると、次のダイアログウィンドウが開きます。
- 中央のペインから空白ページを選択し、[追加]ボタンをクリックします。
- 次に、上記の手順に従ってページをもう1つ追加します。
ソリューションエクスプローラーには、 MainPage、BlankPage1 、および BlankPage2 の3つのページが表示されます。
以下に示すのは、2つのボタンが追加された 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 の2つのボタンのC#コードで、他の2つのページに移動します。
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>
ボタンのC#コード-メインページに移動する*空白ページ1 *のイベントをクリックします。
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));
}
}
}
上記のコードをコンパイルして実行すると、次のウィンドウが表示されます。
任意のボタンをクリックすると、それぞれのページに移動します。 [ページ1に移動]をクリックすると、次のページが表示されます。
[*メインページに移動] *ボタンをクリックすると、メインページに戻ります。
Windows 10開発-ネットワーキング
最近では、ネットワーク上のWebサービスや他のデバイスと何らかの形で統合された多くのアプリケーションが表示されます。 ネットワークサービスを使用する例として、オンラインの天気コンテンツ、最新のニュース、チャット、またはピアツーピアゲームの取得があります。 これらのアプリは、さまざまなネットワーキングAPIを使用して構築されています。 Windows 10では、ネットワークAPIの速度とメモリパフォーマンス、および開発者に提供する機能と柔軟性の点で改善されています。
能力
ネットワーク化するには、適切な機能要素をアプリマニフェストに追加する必要があります。 アプリのマニフェストでネットワーク機能が指定されていない場合、アプリはネットワーク機能を持たず、ネットワークへの接続は失敗します。
以下は、最もよく使用されるネットワーク機能です。
S.No. | Capability & Description |
---|---|
1 |
internetClient 空港やコーヒーショップなどの公共の場所で、インターネットおよびネットワークへのアウトバウンドアクセスを提供します。 インターネットアクセスを必要とするほとんどのアプリは、この機能を使用する必要があります。 |
2 |
internetClientServer インターネットや空港やコーヒーショップなどの公共の場所からのネットワークからの着信および発信ネットワークアクセスをアプリに提供します。 |
3 |
privateNetworkClientServer 自宅や職場など、ユーザーの信頼できる場所でアプリにインバウンドおよびアウトバウンドのネットワークアクセスを提供します。 |
アプリマニフェストファイルで1つ以上の機能を定義するには、以下の画像をご覧ください。
ユニバーサルWindowsプラットフォーム(UWP)には、次のものをターゲットとするネットワークAPIの大規模なセットが含まれています-
- デバイスの接続状態を照会し、ピアデバイスに接続します。
- REST Webサービスとの通信および
- バックグラウンドで大きなメディアファイルをダウンロードする
ネットワーク技術
ユニバーサルWindowsプラットフォーム(UWP)では、開発者は次のネットワークテクノロジを利用でき、さまざまな状況で使用できます。
ソケット
ソケットは、独自のプロトコルで別のデバイスと通信する場合に使用されます。
- Windows.Networking.Sockets と Winsock の両方を使用して、ユニバーサルWindowsプラットフォーム(UWP)アプリ開発者として他のデバイスと通信できます。
- Windows.Networking.Sockets には、UWP開発者が使用するために設計された最新のAPIであるという利点があります。
- クロスプラットフォームネットワークライブラリまたはその他の既存の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* プロトコルは、Webを介したクライアントとサーバー間の高速で安全な双方向通信を提供します。 ユニバーサル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は、Windows Azureとして2010年2月1日に初めてリリースされました。 その後、2014年3月25日にMicrosoft Azureに名前が変更されました。
*PaaSとIaaS* の両方のサービスを提供し、Microsoft固有のソフトウェアとシステムの両方を含む多くの異なるプログラミング言語、ツール、フレームワークをサポートします。
MicrosoftはWindows 10でクラウドサービスをアップグレードしました。 Microsoftアカウントの統合はWindows 8で導入されましたが、 OneDrive は2007年以来存在しています。 Windows 10では、両方のサービスが更新され、統合と新機能が強化され、より多くのユーザーを引き付けています。
マイクロソフトアカウント
MicrosoftアカウントでMicrosoftのAzureクラウドサービスを使用できます。 もちろん、無料ではありませんが、30日間の無料試用版を使用できます。
最初にWindows 10でマシンをセットアップし、Microsoftアカウントでログインしたとき、Microsoft Azureサブスクリプションに同じアカウントを使用できます。 Microsoft Azureにサインアップするには、ここをクリックhttps://azure.microsoft.com/[[[2]]]
Microsoft Azureにサブスクライブしたら、Azure Portal [[3]] 次のページが表示されます。
データベースに保存したり、仮想マシンを使用したりできます。 モバイルアプリのバックエンドを構築してホストすることもできます。
以下の手順に従って、例を使用してこれを試してみましょう。
- 左ペインの[新規]オプションをクリックします。
- * Web&plus;を選択します[モバイル]> [モバイルアプリ*]を選択し、Webアプリに名前を付けます。
- アプリの送信とデプロイには時間がかかります。 このプロセスが完了すると、次のページが表示されます。 ここでは、Windows(C#)、iOS Androidなどのさまざまな種類のモバイルアプリを選択できます。
- Windows 10について話しているため、Windows(C#)を選択すると、次のページが開きます。
- ここでは、2つのダウンロードオプションを確認できます。 これらはサンプルプロジェクトです。VisualStudioでダウンロードしてビルドするだけで、Microsoft Azureに簡単に発行できます。
- サーバープロジェクトである最初のものをダウンロードしましょう。 zipファイルです。
- ダウンロードが完了したら、これを解凍してVisual Studioで開きます。
- 次に、このアプリケーションをビルドします。 いくつかのエラーがリストされている場合は、再度ビルドします。
- アプリケーションを実行してください。 次のWebページが表示されますが、現在はlocalhostにあります。
- このアプリケーションをクラウドでホストするには、以下に示すように、 Solution Explore の Project オプションを右クリックします。
- メニューから*公開*オプションを選択します。 次のダイアログが表示されます。
- 最初のオプション- Microsoft Azure Web Apps を選択します。 次のダイアログボックスが開きます。
- 次に、メニューから[アカウントの追加]オプションをクリックして、Microsoft Azureアカウントを追加します。
- 資格情報を指定して、[サインイン]をクリックします。 次のダイアログウィンドウが開きます。
- サインインした後、メニュー*既存のWebアプリ*からアプリケーションを選択し、 OK をクリックします。
- 以下に示すダイアログには、名前、サーバー名、URLなど、アプリケーションに関連する情報が表示されます。
- 次に、[接続の検証]ボタンをクリックします。 検証後、[公開]ボタンをクリックすると、アプリケーションが Microsoft Azure でホストされていることがわかります。
Windows 10開発-ライブタイル
この章では、タイルを介したユーザーとの対話について説明します。 Windows 10の象徴的な部分です。 タイルは、*スタート画面*および*スタートメニュー*に表示されます。 つまり、これはアプリケーションアイコンアセットであり、Windows 10オペレーティングシステム全体でさまざまな形式で表示されます。 これらは、ユニバーサルWindowsプラットフォーム(UWP)アプリのコーリングカードです。
タイルの解剖学
タイルには3つの状態があります。
- 基本状態-スタートタイルの基本コンポーネントは、バックプレート、アイコン、アプリタイトルで構成されます。
- 準ライブ状態-番号であるバッジが0〜99の番号を表示できるという違いのみがありますが、基本タイルと同じです。
- ライブ状態-このタイルには、セミライブ状態のタイルのすべての要素が含まれており、写真、テキストなど、必要なものを置くことができる追加のコンテンツプレートも表示されます。
タイルの更新
タイルを更新するには4つの方法があります。
- Scheduled - ScheduledTileNotification でテンプレートと時間を設定できます。
- 定期的-情報がURIから取得され、30分、1時間、6時間など、その期間後に情報をプルする時間を指定できる場合。 etc.
- ローカル-アプリケーションからローカルのものを更新できます。フォアグラウンドまたはバックグラウンドアプリから。
- プッシュ-サーバーから情報をプッシュすることにより、サーバーから更新されます。
タイルを作成するには、指定されたコードに従います。
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プロジェクトを作成しましょう。
- Solution Explorer の Assets フォルダーの下にさまざまなpngファイルが表示されます。
- パッケージマニフェストで既定のタイルとその画像を定義しましょう。
- package.appxmanifest をダブルクリックします。 これにより、マニフェストエディターウィンドウが開きます。
- [ Visual Assets ]タブを選択します。
*指定したサイズのアプリケーションタイルの画像とアイコンを選択できます。* Tile Images and Logos *では、次のようなすべてのロゴにデフォルトの画像が提供されます。
* スクエア71x71ロゴ
* スクエア150×150ロゴ
* スクエア310x310ロゴ
* 店舗ロゴ
* アプリケーションを実行して開始画面に移動すると、アプリケーションのタイルが表示されます。
Windows 10開発-共有契約
この章では、アプリケーション間でデータを共有する方法を学びます。 ユーザーは、誰かと共有したり、別のアプリケーションで使用したりすることに興奮している情報に遭遇することがよくあります。 現在、ユーザーはテクノロジーを使用して他の人とつながり、共有したいと考えています。
ユーザーが共有したい場合があります-
- ソーシャルネットワークとのリンク
- 画像をレポートにコピーする
- ファイルをクラウドストレージにアップロードする
今日のアプリケーションでは、使用するデータをユーザーが共有および交換するためにも使用できるようにする必要があります。 共有は軽量な機能で、UWPアプリケーションに簡単に追加できます。 アプリが他のアプリとデータを交換する方法はいくつかあります。
UWPアプリケーションでは、次の方法で共有機能をサポートできます。
- まず、アプリケーションは、ユーザーが共有したいコンテンツを提供するソースアプリにすることができます。
- 第二に、アプリは、ユーザーが共有コンテンツの宛先として選択するターゲットアプリにすることができます。
- アプリは、ソースアプリとターゲットアプリの両方になることもできます。
コンテンツを共有する
ソースアプリであるアプリケーションからコンテンツを共有するのは非常に簡単です。 共有操作を実行するには、 DataPackage クラスオブジェクトが必要です。 このオブジェクトには、ユーザーが共有したいデータが含まれています。
次のタイプのコンテンツを DataPackage オブジェクトに含めることができます-
- テキストで表示
- ユニフォームリソース識別子(URI)
- HTML
- 書式設定されたテキスト
- ビットマップ
- ファイル
- 開発者定義のデータ
データの共有中に、上記の形式の1つ以上を含めることができます。 アプリケーションで共有をサポートするには、まず 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!");
}
アプリケーションが共有するコンテンツには、2つのプロパティが含まれている必要があります-
- Titleプロパティ。必須であり、設定する必要があります。
- コンテンツ自体。
共有コンテンツの受信
アプリケーションが共有コンテンツを受信できるようにする場合、最初に行う必要があるのは、 Share Contract をサポートすることを宣言することです。 宣言後、システムはアプリケーションがコンテンツを受信できるようにします。
共有契約のサポートを追加するには-
- package.appmanifest ファイルをダブルクリックします。
- *宣言*タブに移動します。 [利用可能な宣言]リストから[ターゲットの共有]を選択し、[追加]ボタンをクリックします。
- アプリケーションがあらゆる種類のファイルを共有コンテンツとして受信するようにする場合は、ファイルの種類とデータ形式を指定できます。
- サポートするデータ形式を指定するには、 Declarations ページの Data Formats セクションに移動して、 Add New をクリックします。
- サポートするデータ形式の名前を入力します。 たとえば、 "Text" 。
- サポートするファイルタイプを指定するには、*宣言*ページの*サポートされているファイルタイプ*セクションで、*新規追加*をクリックします。
- サポートするファイル名拡張子を入力します(例: .pdf )
- すべてのファイル*タイプをサポートする場合は、 *SupportsAnyFileType ボックスをチェックします。
- ユーザーがアプリケーションをデータ共有のターゲットアプリケーションとして選択すると、 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;
}
Webリンクを共有する新しい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();
}
}
}
上記のコードをコンパイルして実行すると、エミュレーターに次のページが表示されます。
ボタンをクリックすると、どのアプリケーションで共有するかのオプションが表示されます。
メッセージングをクリックすると、次のウィンドウが表示され、そこから誰にでもリンクを送信できます。
Windows 10 Dev-Windowsへの移植
この章では、既存のアプリWindows 8.1アプリケーションをユニバーサルWindowsプラットフォーム(UWP)に移植する方法を学習します。 顧客がすべての種類のデバイスにインストールできる単一のWindows 10アプリパッケージを作成できます。
アプリケーションをWindows 10 UWPに移植した後、アプリは次の恩恵を受けます-
- 刺激的な新しいハードウェア
- 大きな収益化の機会
- 最新のAPIセット、
- アダプティブUIコントロール、
- 適応設計とコード
- マウス、キーボード、タッチ、音声などのさまざまな入力モダリティ。
Windows 8.xプロジェクトをUWPプロジェクトに移植する
既存のWindows 8.xアプリケーションをユニバーサルWindowsプラットフォーム(UWP)に移植するには、2つのオプションがあります。
- オプション1 *-1つは、Visual Studioで新しいWindows 10プロジェクトを作成し、そこにファイルをコピーすることです。
- オプション2 *-もう1つのオプションは、アプリパッケージマニフェストを含む既存のプロジェクトファイルのコピーを編集することです。
以下は、最初のオプションを使用する際の主な手順です。
- Microsoft Visual Studio 2015を起動し、 UWPBookStore という名前の新しい空のアプリケーション(Windowsユニバーサル)プロジェクトを作成します。
- 新しいプロジェクトは、すべてのデバイスファミリで実行されるアプリパッケージ(appxファイル)をビルドします。
- Universal 8.1アプリプロジェクトで、再利用するすべてのソースコードファイルとビジュアルアセットファイルを特定します。 以下に示すのは、3つのプロジェクトを持つサンプルアプリケーションです。 1つはWindows用、2つ目はモバイル用、3つ目はWindowsとモバイル用の共有プロジェクトです。
- このアプリケーションを電話で実行すると、次のウィンドウが表示されます。
- ウィンドウアプリケーションを実行すると、次のアプリケーションが表示されます。
- 次に、新しく作成したUWPプロジェクトアプリケーションを開きます
- 共有プロジェクトから、ブックカバー画像(.png)ファイルを含む Assets \ CoverImages フォルダーをコピーします。 また、 ViewModel フォルダーと MainPage.xaml をコピーし、宛先のファイルを置き換えます。
- Windowsプロジェクトから、 BookstoreStyles.xaml をコピーします。 このファイルのすべてのリソースキーは、Windows 10アプリで解決されます。 同等の WindowsPhone ファイルにあるものはそうではありません。
- *ソリューションエクスプローラー*で、*すべてのファイルを表示*がオンになっていることを確認します。
- コピーしたファイルを選択して右クリックし、以下に示すように[プロジェクトに含める]をクリックします。
- これには、含まれるフォルダーが自動的に含まれます。 必要に応じて、*すべてのファイルを「オフ」*に切り替えることができます。
- これで、 Solution Explorer でプロジェクト構造は次のようになります。
- コピーしたソースコードとマークアップファイルを編集し、 Bookstore1_81 名前空間への参照を UWPBookStore 名前空間に変更します。
- 最も簡単な方法は、ネームスペースを Replace In Files 機能に置き換えることです。 ビューモデルでコードを変更する必要はありません。
- これで、上記のコードが実行されると、以下に示すように、ローカルマシンとモバイルで実行できます。
次に、2番目のオプションは、アプリパッケージマニフェストを含む既存のプロジェクトファイルのコピーを編集することです。 プロジェクトファイルと package.appmanifest ファイルは、Windows/phone 8.xからWindows 10に移植する際にいくつかの変更が必要です。
マイクロソフトはUWPプロジェクトアップグレードユーティリティを提供しています。これは、既存のアプリケーションを移植する際に非常に役立ちます。 このユーティリティは、https://github.com/Win10DevGuideMVA/ProjectUpgradeUtility/[github.com]からダウンロードできます。
理解を深めるために、上記の例を順を追って実行することをお勧めします。