Вы находитесь на странице: 1из 414

-

-
2013
681.3.06
32.973.26-018.2
88

, . .
88 Windows 8 C# / . . ,
. . , . . . .: -, 2013. 416 .: .
( )
ISBN 978-5-9775-0846-9
Windows Store- Windows 8
C# Visual Studio 2012. -
.
. c
, , , , -
. , -
-
Windows Store.

681.3.06
32.973.26-018.2


.
.




31.10.12.
1
70 100 /16. . . . . 33,54.
3000 .
"-", 191036, -, ., 20.
""
199034, -, 9 , 12/28

ISBN 978-5-9775-0846-9 . ., . ., . ., 2013


, "-", 2013

Windows,
.......................................................................................................... 9
.......................................................................................................................... 11
....................................................................................................... 11
.................................................................................................................. 12
................................................................................................................................ 14

1. Windows 8 .................................................................................. 15
Windows Store-........................................................................................................... 16
............................................................................................................... 21
Windows Store- ............................................................................................. 23
............................................................................................................................................... 25

2. .......................................................................................... 26
............................................................................................................................................... 30

3. Windows Store- ........................................................... 31


Visual Studio ................................................................................................. 31
.................................................................................................... 35
...................................................................................................... 40
............................................................................................ 46
....................................................................... 49
............................................................................................................................................... 52

4. .................................................... 53
.................................................................................. 53
............................................................................................................. 56
............................................................................... 60
.................................................................................... 61
........................................................................... 62
................................................................................................................... 64
.................................................................................................67
............................................................................................................................................... 68
4

5. .......................................................................................... 69
..................................................................................................... 70
............................................................................................................... 72
............................................................................................................................................... 75

6. ...................................................................................... 77
C ..................................................................................................... 79
IsSticky ............................................................................................................................ 83
................................................................................... 83
............................................................................................................................................... 86

7. RSS- Grid App................................................. 87


............................................................................................................................................... 97

8. GridView, ListView FlipView ............................. 98


GridView ...................................................................................................... 99
GridView................................................................. 110
GridView .......................................................... 114
(Semantic Zoom)...................................................................... 115
ListView ..................................................................................................... 120
FlipView..................................................................................................... 123
............................................................................................................................................. 124

9.
.................................................................................. 125
............................................................................................ 126
Visual State Manager ..................................................................................................................... 130
................................ 133
............................................................................................................................................. 135

10. .
................................................................................................. 136
............................................................................................... 136
.................................................................................... 139
/ .................................................................................... 139
........................................................................................................................... 142
........................................................................................................... 146
............................................................................................................................................. 150

11. .............................................................................................. 151


........................................................................................................151
Push- ........................................................................................................................ 155
WNS-. Windows Store.............. 156
Push- ....................................................................................................... 157
............................................................................................................................................. 161

12. "" ....................................................................................... 162


................................................................................................................. 162
"" .......................................................................................................... 163
5

................................................................................................ 166
.......................................................................................................................... 169
........................................................................................... 170
......................................................................................... 171
............................................................................................................................ 172
............................................................................................................... 173
............................................................... 175
............................................................................................................... 177
............................................................................................................................................. 179

13. "" .................................................................................... 180


"" ...................................................................................................182
........................................................................................................ 186
.............................................................................................. 188
........................................................................... 191
............................................................................................................................................. 193

14. " " ...................................................................... 194


.................................................................................................196
...................................................................................................199
.................................................................................................202
...................................................................... 203
....................................................................................................206
............................................................................................................................................. 208

15. "" ........................................................................... 209


................................................................................................209
............................................................................................ 213
............................................................................................................................................. 215

16. .................................................................. 216


......................................................................................................... 216
...................................................................................................................... 218
......................................................................................................................... 219
........................................................... 221
SQLite ................................................................................................................. 221
............................................................................................................................................. 228

17. .................................................... 229


FileOpenPicker ........................................................................................................ 229
FileSavePicker ......................................................................................................... 232
FolderPicker ............................................................................................................ 233
..................................... 233
File Open Picker ................................................................................................... 235
File Save Picker ....................................................................................................239
StorageApplicationPermissions .................. 239
.................................................................. 240
............................................................................................................................................. 244
6

18. ....................................................................................... 245


CameraCaptureUI .............................................................................................. 245
....................................................................... 249
PhotoSettings.AllowCropping ............................................................................................... 249
PhotoSettings.CroppedAspectRatio ....................................................................................... 249
PhotoSettings.CroppedSizeInPixels ....................................................................................... 249
PhotoSettings.Format ............................................................................................................ 250
PhotoSettings.MaxResolution ................................................................................................ 250
.................................................................................. 251
VideoSettings.AllowTrimming ............................................................................................... 251
VideoSettings.Format ............................................................................................................ 251
VideoSettings.MaxDurationInSeconds .................................................................................. 251
VideoSettings.MaxResolution ................................................................................................ 252
MediaCapture / ...................... 252
MediaCapture .......................................................... 256
............................................................................................................................................. 258

19. ............................. 259


....................................................................................... 259
...................................................................................................260
................................................................................. 264
Bing Maps SDK ............................................................................................................. 267
............................................................................................................................................. 274

20. .................................................................................... 275


................................................................................................................................. 275
............................................................................................................................... 278
....................................................................................................................................... 281
................................................................................................................................ 282
.......................................................................................................................................... 286
....................................................................................................... 287
............................................................................................................................................. 288

21. ............................................................................. 289


................................................................................................................................ 290
.............................................................................. 291
....................................................................................... 293
.......................................................................................................... 296
..................................................................... 297
............................................................................................ 298
............................................................................................................................................. 299

22. Windows 8 ................. 300


Windows 8.................................................................................................300
Windows ....................................................................... 303
................................................................................................. 303
................................................................... 307
- .................................................................................... 311
7

......................................................................................... 314
............................................................................................................316
............................................................................................................................................. 318

23. ,
Windows 8 .............................................................. 320
............................................................................................. 321
1. ...........................................................................................321
2. ? .......................................................................... 324
3. ....................................................................................... 325
4. ................................................................................................329
5. .................................................................................... 344
............................................................................................................................................. 353

24. Windows Store ....................... 354


Windows Store .......................................................................................................... 356
Windows Store ........................................................................................................... 358
Windows Store...................................................................................................... 358
........................................................................................... 362
Windows Store ............................................. 363
- ........................................................................................................... 366
............................................................................................................................................. 368

.......................................................................................................... 371
1. XAML .................................................................... 373
........................................................................................................... 376
................................................................................................................. 378
XAML- ........................................................................................ 381
................................................................................................ 383
............................................................................................................. 384
..................................................................................................................... 389
DataContext............................................................................................................ 392
................................................................................................. 396
............................................................................................................................................. 398

2. C# 5 ...................................... 399
async await C# 5......................................................................................... 403
............................................................................................................................................. 407

.............................................................................................. 409
8
Windows,


Windows
1985 .
1,3 !
-
.
,
, .
Windows -
. Windows 8 Microsoft,
, "" -
.
Windows 8 Microsoft
Office, Windows Phone, Visual Studio, Outlook.com ( Hotmail), Microsoft
Account ( Live ID), , . . , Microsoft -
, Windows
.
, . -
Windows ,
, .
Windows 8
.

Windows Store. Windows -
. , -
, , ( ,
) , -
. Windows Store , -
,
Windows, , .
10 Windows,

, , -
, -
C# XAML,
Microsoft, C++ DirectX, ,
HTML 5 JavaScript, Web- .
Windows Windows 3.1. ,
, ,
, .
, , -
, . . .
, , ,
Windows 8.
.

. , , , -
, !


Microsoft
mik@microsoft.com
http://twitter.com/mixen


Windows Store- Windows 8. -
API -
.


C#, -

.
C# , --
, Java,
. -
API (Application Programming Interface, -
) Windows 8, -
C# . C# -
.
:
 Microsoft .NET, WPF,
Silverlight, ASP.NET . .,
Windows 8 .
 Windows, -
Win32 API, MFC, Qt . .,
Windows 8.
 , ,
Windows Phone, Windows Mobile, Android iOS, -
Windows 8.
, Windows 8, -
, -
. , -
, .
12


24- .
.
1 Windows 8.

Windows Store-.
2 ,
Windows Store-: Microsoft Visual Studio, Blend . .
3 Windows 8
, . -
Windows Store- , .
4 Windows Store-
C#. ,
, .
5
: .
6 (Application Bar) -
Windows Store-. -
.
7 RSS- Grid App.
8 GridView ListView,
Windows Store-. -
, .
9 (
320 ) VSM (Visual State
Manager)
.
10
Windows 8, ,
.
11 , ,
Push-, .
12 (Tiles) -
-
.
13
Windows 8 Windows Store-. -
.
14 (Share),
Windows Store-.
13

"-". , -
, .
15 "-" ""
(Settings), .
16 " " .
, . Windows 8
. , -
. -
, . -
, -
. SQLite.
17 .
, Windows Store-
.
. -
, .
, .
18 c Web- -
/ , ,
. , .
19
Microsoft.
20 : ,
, , .
, ,
,
.
21 Windows Store-.
,
.
22 Windows 8. -
Windows 8, Microsoft (-
, Windows Phone, Xbox 360 Visual Studio 2012), -
, -
. ,
.
23
Windows 8.
, , ,
, Windows 8 Windows
Phone, -
(UX UI).
14

( ) -
Windows 8 ,
Web-. "-
" , -
, -
.
, , -
,
, -
( ) -
. Windows Store-
, .
24 Windows Store. -
, .
, .
Windows App Certification Kit , -
, ,
. -
.
1 XAML -
XAML-.
2 . -
, , async await
C# 5.

ftp://ftp.bhv.ru/9785977508469.zip www.bhv.ru.

, :
, , , ,
, , .
, -
, .
"--
" ,
.
Taa1

Windows 8

, Apple iPad,
Windows
, :
1. ,
(Windows 8 , ,
ARM-) , , ,
.
2. (-).
3. .
Windows,
Microsoft
, , .
Windows 95
.
Windows 8 .
Windows Windows Store ,
( ) -
, , .
, Windows 7, Windows 8.
Windows Store , -
Windows Runtime (WinRT). -
Windows Store-. Windows 8 -
. ,
(. 1.1).
Windows Runtime Windows API " -
" Win32 API. Windows
:
16 1

1. Windows-.
2. Windows Store-.
Windows Store- C# Windows Runtime
. -
, API -
.

. 1.1. Windows 8

Windows Store-
, Windows Store-
( , "", "" ""),
. ,
(. 1.2).
Windows Store- -
,
( 30 -

). (. 1.3):
 (Full Screen);
 ( ) (Snapped).
320 ;
Windows 8 17

. 1.2. Windows 8,

. 1.3.


(Filled).
, Windows Store-
. ,
1366768 . -
,
Windows Store-.
, Windows Store- -
(. 1.3), . -
, , -
(Portrait) ( . 1.3).
(Landscape) .
18 1

Windows Store- -
, , , .
.
, -
. API
, Win-
dows 8 , -
.
Windows Store- , , -
, , -
.
(App Bar) "-" (Charms).
, Windows Phone,
Windows 8 .
(. 1.4) ,
(
: ).
( , , -
), -
. ,

. , -
, , , , -
(, -
) ( , -
). :
, -
. , , -
,
, .

. 1.4.
Windows 8 19

Windows 8 "-" (Charms) (. 1.5) -


, ,
, .
,
. "-" :
 , - .
, -
, .
, . .
"-";
 -
. ,
, .
;
 , -
, ;
 ;
 "" Windows, , -
.

. 1.5. "-"

"-" ,
(, , )
.
, -
"" (Tile) (. . 1.1). ,
. ,
, .
20 1

Web-, Push-.
Windows Store- -
.
, -
. 1.6.

. 1.6. ,

(Secondary Tiles) -
.
.
, , "-" -
, -
.
Windows Store- ,
.
Windows 8 21


Windows
API: (native) Win32 API
(managed) .NET Framework. ,
-
( WPF, Windows Presentation Foundation), -
, , -
.
, Windows, . . Win32 API -
. , -
COM (Component Object Model),
90- . . -
, , ,
-, , . . , ,
, . Windows 95 -
, Windows 8 -
.
, Windows, Microsoft ,
API, , (native) -
, . -
Windows Runtime (WinRT).
Windows Runtime , -
(API),
-
. , 50 ,
. . -
"" .

2.

WinRT COM, -
-
, .NET Framework. API, -
WinRT, ,
Windows Store-.
Windows Store- -
: C#, JavaScript, Visual Basic C++. ,
WinRT (
JavaScript), C#, ,
, C++ JavaScript.
WinRT "" -
. WinRT
22 1

, , ,
COM C#. .NET
Framework WinRT .
, JavaScript,
HTML 5, XAML (eXtensible Application
Markup Language ).
XAML WPF Silverlight. XAML -
Windows Phone. XAML Windows
Runtime, ,
Windows.
Windows Store- . -
, -
. , -
. , -
, ,
,
. , , -
. -
.
Windows 8 . 1.7.

. 1.7. Windows 8

Windows Store- C#
XAML. -
. C# , ,
http://bhv.ru/books/book.php?id=188312. XAML -
1.
Windows 8 23

Windows Store-
Windows Store- ()
, Microsoft,
.
Windows 8, Windows Phone, Xbox, Web- ,
http://outlook.com .
Windows 8 Microsoft
(Bauhaus), ( International Typographic
Style) (Motion Design).
, -
-
: , , ,
(. 1.8). , -
. , ,
.
, -
. -
, . -

. 1.8. Windows 8
24 1

, . . Win-
dows Store- , . ,
, , ,
.
(-
, , ,
- :
). ,
( ), -
. -
.
" " . -
. Windows Store- , -
. , ,
Windows 8.
Windows Store- - . ,

. , iPad iBooks,
. .
. -
Windows (. 1.9). ""

. 1.9.
Windows 8 25

, , -
( ).
, . -
, , (
). Windows 8, , -
. -
.
, ,
. Windows 8 ,
, . ,
, .

Windows 8,
Windows Runtime (WinRT),
Windows Store-.
Windows .
Windows 8 ,
, Windows.
Windows
Store-, .
Taa2

Windows,
Windows Store-, Windows--
MSDN (Microsoft Software Development Network):
http://msdn.microsoft.com/windows
:
http://msdn.microsoft.com/ru-ru/windows
Windows- SDK (Software
Development Kit), , . .
Windows Store- x86 x64
Windows 8. Windows Store-
Windows Windows RT ARM- .
Windows 8, (
) 90- . 90-
, . ,
Windows Store-,
Windows .
,
DreamSpark Premium,
Windows 8. .
, Windows 8, -
Windows Store-.
Microsoft
Visual Studio, . Microsoft
Express- Visual Studio 2012, Windows Store-
. Visual Studio Express 2012 for
Windows 8. Windows Store- -
27

Visual Studio 2012,


Ultimate, Premium Professional.
Visual Studio 2012,
Visual Studio Express 2012.
, -
, .
Visual Studio Express 2012 for Windows 8 -
Windows Store. Store
Visual Studio, (. 2.1), Go
to publishers website.

. 2.1. Visual Studio Express 2012 Windows Store

Visual Studio Express for Windows 8 ,


Windows 8 SDK, Blend for Visual Studio. Blend
Visual Studio.
Blend ()
. ,
Blend, , , WPF
(Windows Presentation Foundation), Windows Phone. Blend
for Visual Studio Windows Store-.
Windows Store- Visual Studio,
Blend. Blend ,
, Visual Studio -
28 2

. Blend , -
, VSM (Visual State Manager) -
. . Blend , ,
, Visual Studio.
, Blend , -
XAML C# (
HTML JavaScript JavaScript-). ,
Blend, Visual Studio.
Visual Studio Blend ,
. -
, Blend, Visual Studio -
, .
. 2.2 Visual Studio, . 2.3 Blend -
Windows Store-.
Visual Studio, Blend , -
. Visual Studio , TOOLS |
Options..., Environment | General, -
, Color theme. Visual Studio
. 2.4.
Blend , Tools | Options...,
Workspace, ,
Theme.

. 2.2. Visual Studio Express 2012 for Windows 8


29

. 2.3. Blend for Visual Studio

. 2.4. Visual Studio


30 2

Visual Studio Express 2012,


, Windows MSDN:
 Live SDK
Microsoft (Microsoft Account, Windows Live ID),
SkyDrive .
 Windows 8 Ads in Apps SDK -
. ,
, .
.
 Multilingual App Toolkit for Visual Studio 2012 Visual Studio,
Windows Store-. -
.
 Remote Tools for Visual Studio 2012
, Visual
Studio. Win-
dows Store- Windows RT, ARM-,
Visual Studio .
 Sample app pack Windows Store-,
. , -
, Sample app
pack , .
, -
Bing Maps SDK.
19.

, -
Windows Store-. , Windows 8, -
90- .
Windows Store- .
Visual Studio Express 2012 for Windows 8 (
Visual
Studio 2012).
, Visual Studio 2012
Blend for Visual Studio.
, Win-
dows Store-, .
Taa3

Windows Store-

Visual Studio,
Windows Store-.
"Hello World", . -
,
, , ,
, -
c ARM- Windows RT.

Visual Studio
Visual Studio Express 2012 for Windows 8
Visual Studio 2012, .
, Express-.

,
. Windows Store-
, Visual Studio 2012 -
.
Visual Studio Express ,
(. 3.1). Visual Studio -
Windows Store-,
Visual Studio.
Windows Store-
Windows 8 -
Windows Store. , -
, ,
( ). -
, . . .
32 3

, -
.

Windows Store. ,
Windows Store . Windows Store, -
.

. 3.1.

I Agree.
, -
.
Microsoft (Microsoft
account, Windows LiveID).
(. 3.2) Sign in.
, -
(. 3.3).
,
Visual Studio Express STORE | Acquire Developer Licence... PROJECT |
Store | Acquire Developer Licence... Visual Studio.
Windows Store-. File |
New Project. New Project
Installed | Templates Visual C#, Windows
Store. New Project -
, -
Blank App (XAML). Name ,
HelloWorldApp, Location , -
. OK (. 3.4). -
Windows Store- 33

. 3.2. Microsoft

. 3.3. ,

Windows Store-, C#- -


App.xaml (. 3.5).
, <F5> -
,
Debug | Start Debugging. , -
. ,
.
34 3

. 3.4. Windows Store-

. 3.5. Windows Store-

, .
-
. (Tile) (
. 3.6, ).
Windows Store- 35

. 3.6.


Windows Store-, ,
. Solution
Explorer Visual Studio (. 3.7).
 MainPage.xaml
XAML. , -
. App.xaml.cs,
.
MainPage.xaml. ,
. Windows 8 -
,
, -
. Windows Store-
. 4.
 MainPage.xaml.cs (code-behind) C#
MainPage.xaml. - ,
xaml.cs.
36 3

MainPage.xaml.cs. ,
MVVM (Model-View-ViewModel),
, -
.
, , -
MVVM.
 App.xaml Windows Store-
XAML.
. App.xaml -
. ,
, -
, .
( ) .

. 3.7.
Windows Store-

App.xaml 3.1.

3.1. App.xaml

<Application
x:Class="HelloWorldApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:HelloWorldApp">

<Application.Resources>
<ResourceDictionary>
Windows Store- 37

<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Common/StandardStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>

</ResourceDictionary>
</Application.Resources>
</Application>

StandardStyles.xaml.
.
 App.xaml.cs (code-behind) C# App.xaml.
, , -
, , .
, App.xaml.cs -
.
 StandardStyles.xaml -
. , App.xaml
. ,
, -
. StandardStyles.xaml
, ,
. -
.
 Package.appxmanifest . -
, , (Tiles) -
(Splash Screen), , -
. . ,
XML-, ,
Visual Studio (. 3.8). -

Package.appxmanifest Solution Explorer.
Application UI, Capabilities, Declarations
Packaging, .
, , 3.2
Package.appxmanifest . ,
, Publisher, .

3.2. Package.appxmanifest

<?xml version="1.0" encoding="utf-8"?>


<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">

<Identity Name="f1e59aea-15c7-4515-89ba-1976f2499f4f"
Publisher="CN=v-sepuga"
Version="1.0.0.0" />
38 3

<Properties>
<DisplayName>HelloWorldApp</DisplayName>
<PublisherDisplayName>v-sepuga</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
</Properties>

<Prerequisites>
<OSMinVersion>6.2.1</OSMinVersion>
<OSMaxVersionTested>6.2.1</OSMaxVersionTested>
</Prerequisites>

<Resources>
<Resource Language="x-generate"/>
</Resources>

<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="HelloWorldApp.App">
<VisualElements
DisplayName="HelloWorldApp"
Logo="Assets\Logo.png"
SmallLogo="Assets\SmallLogo.png"
Description="HelloWorldApp"
ForegroundText="light"
BackgroundColor="#464646">
<DefaultTile ShowName="allLogos" />
<SplashScreen Image="Assets\SplashScreen.png" />
</VisualElements>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
</Capabilities>
</Package>

 AssemblyInfo.cs ,
(Assembly) .
 HelloWorldApp_TemporaryKey.pfx -
, .
 Logo.png, SmallLogo.png, StoreLogo.png -
, . -
, . .
. -
, . -
Windows Store- 39

. 3.8.

,
12.
,
.
 SplashScreen.png , -
. ,
, -
. - .
References,
.NET-.
(Assemblies) (Frameworks), .
40 3

: .NET for Windows Store apps Windows,


.NET Framework Windows Runtime -
.


(. 3.9)
MainPage.xaml
Solution Explorer. , Windows
Store-, C#,
XAML (. 1). Visual Studio XAML-
, WYSIWYG (What You See Is What
You Get, " , "). Visual Studio -
Windows Store- -
. WYSIWYG,
, XAML-.
, -
, , ,
, ,
, , XAML-
.

. 3.9.
Windows Store- 41

, ,
Toolbox -
Properties, -
XAML- .
XAML-.
, XAML-
MainPage.xaml ( 3.3).

3.3.

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

<Grid
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

</Grid>
</Page>

. -
, Basic Page. . XAML-
Page,
Grid (), .
ApplicationPageBackgroundThemeBrush, -
( ).
XAML- C#,
MainPage.xaml.cs. C#- , View Code -
XAML-.
C#- MainPage 3.4.

3.4. C# MainPage

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
42 3

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;

namespace HelloWorldApp
{
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}

protected override void OnNavigatedTo(NavigationEventArgs e)


{
}
}
}

MainPage, -
( this.InitializeComponent). -
OnNavigatedTo, .
" !",
"Hello World".
Grid ( 3.5).

3.5. " !"

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">


<Button Content=" !"
HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>

Grid -
, (HorizontalAlignment="Center"),
(VerticalAlignment="Center"). -
(. 3.10).
.
XAML-
Click Button. Click XAML-
(<New Event Handler>)
Windows Store- 43

(. 3.11).
. ,
Button_Click_1. -
. -
, -
.

. 3.10. " !"

. 3.11.

C#- ,
XAML- Navigate
to Event Handler. C#-,

( 3.6).

3.6.

public sealed partial class MainPage : Page


{
public MainPage()
44 3

{
this.InitializeComponent();
}

protected override void OnNavigatedTo(NavigationEventArgs e)


{
}

private void Button_Click_1(object sender, RoutedEventArgs e)


{

}
}

. -
. "Hello
World!" ( 3.7).

3.7.

private void Button_Click_1(object sender, RoutedEventArgs e)


{
var dlg = new MessageDialog("Hello World!");
dlg.ShowAsync();
}

. -
(. 3.12).
MessageDialog Windows.UI.Popups -
, , . -
( 3.8).

. 3.12. "Hello World!"


Windows Store- 45

3.8.

var dlg = new MessageDialog("Hello World!", "");


dlg.ShowAsync();

. :
1, 2 3 ( 3.9). -
, .
(dlg.DefaultCommandIndex = 1).
-
<Enter>. , -
<Escape>.
.
, Button_Click_1 -
, async.
await ( async await 2).
, .
, ,
Id, .

3.9.

private async void Button_Click_1(object sender, RoutedEventArgs e)


{
var dlg = new MessageDialog("Hello World!", "");

dlg.Commands.Add(new UICommand(" 1",


new UICommandInvokedHandler((args) =>
{
//
})));

dlg.Commands.Add(new UICommand(" 2"));


dlg.Commands.Add(new UICommand(" 3") { Id = 3 });

dlg.DefaultCommandIndex = 1;
dlg.CancelCommandIndex = 2;

var command = await dlg.ShowAsync();


}

.
. 3.13.
46 3

. 3.13.


, MessageDialog ,
. -
, .


.
,
, , , ,
. 1366768 -
, . -
. ,
-
, , ,
. .
, . . -
, . -
. Windows, -
, .
(Remote
Desktop, RDP).
-
Local Machine Simulator (. 3.14).
.
(. 3.15).
Windows,
, .
,
, .
Windows Store- 47

. 3.14.

. 3.15.

Start, -
"-"
.
13 .
.
 (Minimize).
 (Always on top).
 ,
(Mouse mode).
 , (-
) (Basic touch mode).
 (Pinch/zoom touch mode).
48 3

 .
 90 (Rotate clockwise (90 degrees)).
 90 (Rotate counterclockwise
(90 degrees)).
 (Change resolution).
 (Set location).
 (Copy screenshot).
 (Screenshot settings).
 (Help).
,
. -
. -
(. 3.16).

. 3.16.

, , 10,6 ,
. ,
( PPI, Pixels Per Inch). -
, ,
. , 9.

. , -
Windows Store- 49

, .
, , ,
, . ,
.



, ,
.
, , , .
-
Remote Tools for Visual Studio 2012. ,
. ,
.
, , . 3.17.

. 3.17.

Visual Studio.
Remote Machine . -
(. 3.18).
. -
.
,
, . ,

- . , -
. -
, .
, Visual Studio Express
STORE | Create App Packages... PROJECT | Store | Create App
Packages... Visual Studio. -
Windows Store. "" (No)
(. 3.19).
50 3

. 3.18.


. 3.19.
Windows Store- 51

Next, ( -
). Create.
appx, -
(. 3.20). appx -
. ZIP-,
, ,
HelloWorldApp_1.0.0.0_AnyCPU_Debug.appx zip
.
PowerShell ps1,
,
.


Windows PowerShell Microsoft,
.
PowerShell Windows 8.

. 3.20.


PowerShell Add-AppDevPackage.ps1. ,
.
52 3

Windows Store-
"Hello World".
Windows Store- .
Blank App,
, .
MainPage.xaml ,
C#. ,
.
, , .
,
.
Taa4



Win-
dows Store-: . 3 -
, MainPage.xaml,
. , Web-
. Web-
Windows Store- ( ).
, , -
(,
), . ,
Windows Store- Web-. Windows Store-,
JavaScript, . , -
C#, HTML- JavaScript XAML-
C#. CSS ,
XAML-.
"Hello World" ,
, ,
.


3 MainPage.xaml. -
App.xaml.cs. (-
4.1).

4.1. C#- App.xaml

using System;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
54 4

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

namespace HelloWorldApp
{
/// <summary>
/// , ,
/// Application
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// App
/// Singleton
///
///
/// main() WinMain()
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}

/// <summary>
/// ,
///
/// ,
/// ,
/// . .
/// </summary>
/// <param name="args"> .</param>
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;

// ,
// ,
// ,
if (rootFrame == null)
{
// Frame,
//
rootFrame = new Frame();

if (args.PreviousExecutionState ==
ApplicationExecutionState.Terminated)
55

{
// TODO: ,
// Terminated
}

// Frame
//
Window.Current.Content = rootFrame;
}

if (rootFrame.Content == null)
{
// ,
//
//
//
if (!rootFrame.Navigate(typeof(MainPage),
args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}

// ,
Window.Current.Activate();
}

/// <summary>
///
/// (suspended)
/// ,
/// (tetminated)
/// (resumed)
/// ,
///
/// </summary>
/// <param name="sender"> .</param>
/// <param name="e"> .</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
// TODO:
//
deferral.Complete();
}
}
}
56 4

App, Application,
Package.appxmanifest . -
( , ). -
Main() .NET- (
main() WinMain() , C/C++).

( ) -
OnLaunched .
, . -
.
,
, OnLaunched Frame.
. -
.
( 4.2).

4.2.

rootFrame.Navigate(typeof(MainPage), args.Arguments);

Navigate -
, .
MainPage. .
, . -
Navigate , .


Solution Explorer -
Add | New Item.... ,
, (. 4.1).
Basic Page, SecondPage.xaml -
Add. . -
Yes .
Basic Page , Blank Page. Basic
Page , "", , -
(. 4.2).
XAML- SecondPage.xaml 4.3. ,
,
(VisualStateManager.VisualStateGroups) , .
57

. 4.1.

. 4.2. SecondPage.xaml
58 4

4.3. SecondPage.xaml

<common:LayoutAwarePage
x:Name="pageRoot"
...
>

<Page.Resources>
<x:String x:Key="AppName">My Application</x:String>
</Page.Resources>

<Grid Style="{StaticResource LayoutRootStyle}">


<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<Button x:Name="backButton" Click="GoBack"


IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}"
Style="{StaticResource BackButtonStyle}"/>

<TextBlock x:Name="pageTitle" Grid.Column="1"


Text="{StaticResource AppName}"
Style="{StaticResource PageHeaderTextStyle}"/>
</Grid>

<VisualStateManager.VisualStateGroups>
...
</VisualStateManager.VisualStateGroups>
</Grid>
</common:LayoutAwarePage>

("My Application") XAML-


pageTitle -
. (backButton) -
CanGoBack
. , -
.
BackButtonStyle,
StandartStyles.xaml,
, ( ).
59

,
Common (. . 4.2) .
( Basic Page), -
, .
, MainPage.xaml
SecondPage.xaml.
4.4.

4.4. SecondPage.xaml

private async void Button_Click_1(object sender, RoutedEventArgs e)


{
this.Frame.Navigate(typeof(SecondPage));
}

, MainPage.xaml, Frame,
.
Frame .
, ,
HyperlinkButton ( 4.5).

4.5. HyperlinkButton

<HyperlinkButton Content=" " Click="HyperlinkButtonClick"/>

Click -
. 4.4.
Navigate Frame
(. 4.1).

4.1. Frame

/
GoBack
. ,

GoForward
. -
,
CanGoBack , ,

CanGoForward , ,

CurrentSourcePageType ,
60 4


SecondPage.xaml .
, Grid, -
SecondPage.xaml,
LayoutRootStyle ( 4.6)

4.6. Grid

<Grid Style="{StaticResource LayoutRootStyle}">


...
</Grid>

StandardStyles.xaml
, , ( 4.7).

4.7. LayoutRootStyle

<Style x:Key="LayoutRootStyle" TargetType="Panel">


<Setter Property="Background"
Value="{StaticResource ApplicationPageBackgroundThemeBrush}"/>
<Setter Property="ChildrenTransitions">
<Setter.Value>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Setter.Value>
</Setter>
</Style>

EntranceThemeTransition, -
.
, Grid, .
Windows 8
. ContentThemeTransition.
:
 FadeInThemeAnimation/FadeOutThemeAnimation
 PointerUpThemeAnimation/PointerDownThemeAnimation
 RepositionThemeAnimation/RepositionThemeTransition
 PopInThemeAnimation/PopOutThemeAnimation/PopupThemeTransition
 EdgeUIThemeTransition
 PaneThemeTransition
 AddDeleteThemeTransition
61

 DragItemThemeAnimation/DropTargetItemThemeAnimation/ DragOverThemeAnimation
 SwipeHintThemeAnimation/SwipeBackThemeAnimation

.



.
Navigate Frame. -
, int, string, char, Guid
. . , , ,
, . , -
.
4.8 .

4.8.

this.Frame.Navigate(typeof(SecondPage), " ");

, -
OnNavigatedTo , ( 4.9).
SecondPage.xaml.

4.9. ,

public sealed partial class SecondPage : LayoutAwarePage


{
public SecondPage()
{
this.InitializeComponent();
}

protected override void OnNavigatedTo(NavigationEventArgs e)


{
string parameter = e.Parameter as string;

base.OnNavigatedTo(e);
}

protected override void LoadState(Object navigationParameter,


Dictionary<String, Object> pageState)
{
}
62 4

protected override void SaveState(


Dictionary<String, Object> pageState)
{
}
}

OnNavigatedTo (
). OnNavigateTo
base.OnNavigatedTo(e). , -
.
, . (override) -
, ,
.
SecondPage LayoutAwarePage, -
, .
.
. .


Basic Page
LayoutAwarePage,
. Blank App,
LayoutAwarePage -
. , Grid App Split App,
.
Windows Store- ,
Windows-. -
, Windows
, .
, .
, . -
, ,
.
.

Windows Store- 10.


, (, , ) -
- . , . .
5 . -
, ,
,
.
63

.
SuspensionManager, -
SecondPage.xaml. SuspensionManager
. SuspensionManager -
. -
, SuspensionManager -
.
SuspensionManager App.xaml.cs ( 4.10).

4.10. SuspensionManager

protected async override void OnLaunched(LaunchActivatedEventArgs args)


{
Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null)
{
rootFrame = new Frame();

SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

if (args.PreviousExecutionState ==
ApplicationExecutionState.Terminated)
{
try
{
await SuspensionManager.RestoreAsync();
}
catch (SuspensionManagerException)
{
//
}
}

// Frame
//
Window.Current.Content = rootFrame;
}

if (rootFrame.Content == null)
{
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}

Window.Current.Activate();
}
64 4

private async void OnSuspending(object sender, SuspendingEventArgs e)


{
var deferral = e.SuspendingOperation.GetDeferral();

await SuspensionManager.SaveAsync();

deferral.Complete();
}

, -
. ,
.
, -
. , .
Basic Page LoadState SaveState ( 4.11), -
,
SuspensionManager.
. -
.

4.11. LoadState SaveState

protected override void LoadState(Object navigationParameter,


Dictionary<String, Object> pageState)
{
}

protected override void SaveState(


Dictionary<String, Object> pageState)
{
}

SuspensionManager ( 4.12).

4.12. SuspensionManager

SuspensionManager.SessionState.Add("", "");


. -
.
, , -
, , .
65

SecondPage.xaml
( 4.13).

4.13.

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

<Button x:Name="backButton" Click="GoBack"


IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}"
Style="{StaticResource BackButtonStyle}"/>

<TextBlock x:Name="pageTitle" Grid.Column="1"


Text="{StaticResource AppName}"
Style="{StaticResource PageHeaderTextStyle}"/>
</Grid>

<Grid Grid.Row="1">
<TextBox x:Name="txtMain" Width="250"
VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Grid>

<VisualStateManager.VisualStateGroups>

.
. , -
.
,
, NavigationCacheMode.
Enabled ( 4.14),
, , .
,
.

4.14. NavigationCacheMode

public SecondPage()
{
this.InitializeComponent();

this.NavigationCacheMode = NavigationCacheMode.Enabled;
}
66 4

NavigationCacheMode Required,
.
NavigationCacheMode , -
. -
.
NavigationCacheMode,
( , -
) . -
, LoadState SaveState ( 4.15).
.

4.15.

protected override void SaveState(Dictionary<String, Object> pageState)


{
pageState["text"] = txtMain.Text;
}

protected override void LoadState(Object navigationParameter,


Dictionary<String, Object> pageState)
{
if (pageState == null) return;

if (pageState.ContainsKey("text"))
{
txtMain.Text = pageState["text"] as string;
}
}

,
Debug Location
Visual Studio (. 4.3). ,
VIEW | Toolbars | Debug Location.
,
.

. 4.3. Debug Location


67


HyperlinkButton NavigateUri
, ( 4.16). -
, .

4.16. HyperlinkButton

<HyperlinkButton NavigateUri="http://twitter.com/spugachev"
Content="@spugachev"/>

, . . -
http. , -
. -
(
). ,
mailto, FTP- ftp.
Launcher ( 4.17).

4.17.

Launcher.LaunchUriAsync(new Uri("http://twitter.com/spugachev"));

( 4.18).

4.18.

private async void HyperlinkButtonClick(object sender, RoutedEventArgs e)


{
var opts = new LauncherOptions();
opts.TreatAsUntrusted = true;
opts.DisplayApplicationPicker = true;
opts.PreferredApplicationDisplayName = " ";
opts.PreferredApplicationPackageFamilyName = "MyAppFamilyName";

var success = await Launcher.LaunchUriAsync(


new Uri("someprotocol://data"), opts);
if (success)
{
//
}
else
{
//
}
}
68 4

TreatAsUntrusted ,
.
DisplayApplicationPicker ,
.
, , ,
Windows
Store. PreferredAppli-
cationDisplayName PreferredApplicationPackage-
FamilyName. -
, .
Launcher .
LaunchFileAsync. ,
.
, .
Windows Store--
. -
Launcher.


17.


App.xaml.cs, .
-
. , , ,
Windows Store-
.
.
.
.
Taa5

, .
,
. ( -
), -
.
XAML, -
1, .

ApplicationPageBackgroundThemeBrush ( 5.1).

5.1.

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">


...
</Grid>

. -
, . , , -
ApplicationPageBackgroundThemeBrush, ,
. . -
, .
Windows Phone, ,
Windows Phone Windows 8 . Win-
dows Phone , Windows 8 -
.
70 5


Grid App. , -
Grid App, ,
GroupedItemsPage.xaml.
, (. 5.1).

. 5.1. ,

. App.xaml. -
RequestedTheme Light
( 5.2).

5.2.

<Application
x:Class="ThemeApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:ThemeApp"
xmlns:localData="using:ThemeApp.Data"
RequestedTheme="Light">

(. 5.2). -
.
71

. 5.2. ,

App ( 5.3).

5.3.

public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;

RequestedTheme = ApplicationTheme.Light;
}

Visual Studio ,
( ).
Device, Visual Studio. ,
DESIGN | Device Window . Device -
(. 5.3).
Device
.
72 5

. 5.3. Device


TextBlock ( 5.4).

5.4.

<TextBlock Text="- " />

, (-
5.5).

5.5.

<TextBlock Text="- " FontFamily="Times New Roman" FontSize="24"/>

, -
( , , ). -
, , -
, .


15 , . . .

,
BasicTextStyle ( 5.6).

5.6.

<TextBlock Text="- "


Style="{StaticResource BasicTextStyle}"/>
73

. 5.4 .
, -
.

. 5.4.

:
 PageHeaderTextStyle  TitleTextStyle
 PageHeaderTextStyle  SubtitleTextStyle
 PageSubheaderTextStyle  ItemTextStyle
 SnappedPageHeaderTextStyle  BodyTextStyle
 HeaderTextStyle  CaptionTextStyle
 SubheaderTextStyle  BasicTextStyle
 GroupHeaderTextStyle  BaselineTextStyle.

. . 5.5 -
, . , ,
, .
StandardStyles.xaml. -
,
.
. -
, Edit Style | Apply
Resource (. 5.6).
.

( 5.7).

5.7.

<TextBlock Text="- " Style="{StaticResource BodyTextStyle}">


<LineBreak/>
<Run Foreground="LightGray" FontFamily="Times New Roman"
FontWeight="Bold" FontSize="26">
Times New Roman Bold 26
</Run>
<LineBreak/>
<Run Foreground="Red" FontFamily="Arial" FontSize="24">
74 5

Arial 24
</Run>
</TextBlock>

5.7
. 5.7.

. 5.5. ,

- ,
RichTextBlock ( -
RichEditBox), TextBlock.
RichTextBlobk , .
, -
.
StandardStyles.xaml, ,
MSDN.
75

. 5.6.

. 5.7.

Windows Store-. -
.
App.xaml .
76 5

, ApplicationPageBackgroundThemeBrush
ApplicationForegroundThemeBrush, . , -
. StandardStyles.xaml
, .
, ,
HeaderTextStyle, , .
. -

Windows Store-.
Taa6

(Application Bar)
Windows Store-.
, . ,
, . ,
Application, - , "
", ,
.
, - .
,
.
.
" " "" -
. .

, <Windows>+<Z>,
.
. -
, -
, .
,
.
, , , . -
, . -
, .
. -
, Internet Explorer
( , ).
. 6.1 Internet Explorer , . 6.2 .
78 6

. 6.1. Internet Explorer

. 6.2. Internet Explorer


79

Internet Explorer -
. .
, -
(. 6.3). .

. 6.3.

C

BottomAppBar TopAppBar ( 6.1). -
AppBar.

6.1.

<Page
...
>
<Page.TopAppBar>
<AppBar x:Name="topAppBar" Padding="10,0,10,0">
<!-- -->
</AppBar>
</Page.TopAppBar>
<Page.BottomAppBar>
80 6

<AppBar x:Name="bottomAppBar" Padding="10,0,10,0">


<!-- -->
</AppBar>
</Page.BottomAppBar>

<Grid
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">

</Grid>
</Page>


( 6.2). Grid
( ).

6.2.

<AppBar x:Name="bottomAppBar" Padding="10,0,10,0">


<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Button />
<Button />
<Button />
</StackPanel>
<StackPanel Grid.Column="1"
HorizontalAlignment="Right" Orientation="Horizontal">
<Button />
</StackPanel>
</Grid>
</AppBar>

.
,
Windows Store-, (-
).
AppBarButtonStyle.
,
AutomationProperties.Name ( 6.3).

6.3.

<Button Style="{StaticResource AppBarButtonStyle}"


AutomationProperties.Name=""/>
81

. 6.4.
AppBarButtonStyle

. 6.4 , AppBarButtonStyle.
StandardStyles.xaml . -
. .
,
StandardStyles.xaml ( 6.4).

6.4.

<AppBar x:Name="bottomAppBar" Padding="10,0,10,0">


<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal">
<Button Style="{StaticResource AppBarButtonStyle}"
AutomationProperties.Name=""/>
<Button Style="{StaticResource PageAppBarButtonStyle}" />
<Button Style="{StaticResource VideoChatAppBarButtonStyle}"/>
</StackPanel>
<StackPanel Grid.Column="1"
HorizontalAlignment="Right" Orientation="Horizontal">
<Button Style="{StaticResource BulletsAppBarButtonStyle}" />
</StackPanel>
</Grid>
</AppBar>

. 6.5. ,
. ,
AutomationProperties.Name.

. 6.5.
82 6

,
StandardStyles.xaml . -
. 6.6.
. 6.6 .
.

. 6.6.
83

IsSticky

. -
(
. .), IsSticky ( 6.5).

6.5. IsSticky

<AppBar x:Name="bottomAppBar" IsSticky="True">

, , -
IsOpen, .


-
.
. ,
(. 6.7).
Popup, -
.
.

. 6.7.
84 6


Popup Flyout Windows Store-
, JavaScript.

(-
6.6). .
, (PopupThemeTransition).

6.6.

private void ButtonClick(object sender, RoutedEventArgs e)


{
Popup popup = new Popup();
popup.IsLightDismissEnabled = true;

Grid panel = new Grid();


panel.Background = bottomAppBar.Background;
panel.Height = 250;
panel.Width = 150;

panel.Transitions = new TransitionCollection();


panel.Transitions.Add(new PopupThemeTransition());

Button btnMain = new Button();


btnMain.Content = "";
btnMain.VerticalAlignment = VerticalAlignment.Center;
btnMain.HorizontalAlignment = HorizontalAlignment.Center;
panel.Children.Add(btnMain);

popup.Child = panel;

var button = (Button)sender;


var transform = button.TransformToVisual(this);
var point = transform.TransformPoint(new Point());

popup.HorizontalOffset = point.X;
popup.VerticalOffset = Window.Current.CoreWindow.Bounds.Bottom -
bottomAppBar.ActualHeight panel.Height 4;

popup.IsOpen = true;
}

. 6.8.
(Child),
(HorizontalOffset VerticalOffset) IsOpen true.
85

. 6.8.

,
, . -
PopupMenu ( 6.7).

6.7.

private async void ButtonClick(object sender, RoutedEventArgs e)


{
var popupMenu = new PopupMenu();
popupMenu.Commands.Add(new UICommand(""));
popupMenu.Commands.Add(new UICommand(""));
popupMenu.Commands.Add(new UICommand(""));

var button = (Button)sender;


var transform = button.TransformToVisual(this);
var point = transform.TransformPoint(new Point(45, -10));

await popupMenu.ShowAsync(point);
}

. 6.9.
, MessageDialog, -
. .
-
. , -
.
86 6

. 6.9.

Windows Store--
. .
.
, -
, , -
StandardStyles.xaml.
.

. Popup PopupMenu.
Taa7

RSS-
Grid App
5 Grid App.
, , , -
, . RSS-
Grid App.

RSS- . http://blogs.msdn.com/
b/somasegar/.

. RSS-
. 7.1.

. 7.1. RSS-
88 7

Windows Store- Grid App


RssApp. DataModel, -
SampleDataSource.cs (. 7.2).

. 7.2.
SampleDataSource.cs

. -
.

.
SampleDataSource.cs :
 SampleDataSource
 SampleDataGroup
 SampleDataItem
Grid App , , -
. ,
. -
SampleDataGroup,
SampleDataItem.
, -
AllGroups SampleDataSource.
SampleDataSource ,
.
SampleDataSource.
_allGroups AllGroups , GetGroup
RSS- Grid App 89

GetItem( SampleDataSource)
( 7.1).

7.1. SampleDataSource

public sealed class SampleDataSource


{
public static ObservableCollection<SampleDataGroup> _allGroups =
new ObservableCollection<SampleDataGroup>();

public static ObservableCollection<SampleDataGroup> AllGroups


{
get
{
return _allGroups;
}
}

public static SampleDataGroup GetGroup(string uniqueId)


{
var matches = AllGroups.Where((group) =>
group.UniqueId.Equals(uniqueId));

if (matches.Count() == 1) return matches.First();


return null;
}

public static SampleDataItem GetItem(string uniqueId)


{
var matches = AllGroups.SelectMany(group =>
group.Items).Where((item) => item.UniqueId.Equals(uniqueId));

if (matches.Count() == 1) return matches.First();


return null;
}
}

RSS.
SyndicationClient
Windows.Web.Syndication. RSS-
Atom-, ( 7.2). ,
SyndicationClient , ,
.
RSS, .
HTTP, HttpClient. , -
HTTP, Socket API.
90 7

Windows 8 . -
Web-.
.

7.2. RSS-

var feedClient = new SyndicationClient();


var feed = await feedClient.RetrieveFeedAsync(new Uri(feedUrl));

SampleDataSource AddGroupForFeedAsync,
( 7.3).

7.3.

public static async Task<bool> AddGroupForFeedAsync(string feedUrl)


{
// , false
if (SampleDataSource.GetGroup(feedUrl) != null) return false;

var feedClient = new SyndicationClient();


var feed = await feedClient.RetrieveFeedAsync(new Uri(feedUrl));

var feedGroup = new SampleDataGroup(


uniqueId: feedUrl,
title: feed.Title != null ? feed.Title.Text : null,
subtitle: feed.Subtitle != null ? feed.Subtitle.Text : null,
imagePath: feed.ImageUri != null ?
feed.ImageUri.ToString() : null,
description: null);

AllGroups.Add(feedGroup);
return true;
}

SampleDataGroup -
AllGroups.
. (-
) ,
HTML- . -
GetImageFromPostContents ( 7.4). -
HTML- src href, -
png, jpg jpeg (, <img src="image.jpg" />).
-
.
RSS- Grid App 91

7.4.

private static string GetImageFromPostContents(SyndicationItem item)


{
var regex = new Regex(
"[src href]\\s*=\\s*(?:\"(?<1>[^\"]*)\"|(?<1>\\S+))");

var matches = regex.Matches(item.Summary.Text);

return matches.Cast<Match>()
.Where(m =>
{
Uri url;
if (Uri.TryCreate(m.Groups[1].Value, UriKind.Absolute, out url))
{
string ext = Path.GetExtension(url.AbsolutePath).ToLower();
if (ext == ".png" || ext == ".jpg"
|| ext==".jpeg") return true;
}
return false;
})
.Select(m => m.Groups[1].Value)
.FirstOrDefault();
}

AddGroupForFeedAsync ,
SampleDataItem ( 7.5). -
,
.

7.5.

public static async Task<bool> AddGroupForFeedAsync(string feedUrl)


{
// , false
if (SampleDataSource.GetGroup(feedUrl) != null) return false;

var feedClient = new SyndicationClient();


var feed = await feedClient.RetrieveFeedAsync(new Uri(feedUrl));

var feedGroup = new SampleDataGroup(


uniqueId: feedUrl,
title: feed.Title != null ? feed.Title.Text : null,
subtitle: feed.Subtitle != null ? feed.Subtitle.Text : null,
imagePath: feed.ImageUri != null ?
feed.ImageUri.ToString() : null,
description: null);
92 7

foreach (var i in feed.Items)


{
string imgPath = GetImageFromPostContents(i);

if (imgPath != null && feedGroup.Image == null)


{
feedGroup.SetImage(imgPath);
}

var dataItem = new SampleDataItem(


uniqueId: i.Id,
title: i.Title.Text,
subtitle: null,
imagePath: imgPath,
description: null,
content: i.Summary.Text,
@group: feedGroup);

feedGroup.Items.Add(dataItem);
}

AllGroups.Add(feedGroup);
return true;
}

, . -
.
GroupedItemsPage.xaml. -
( 7.6).

7.6.
GroupedItemsPage.xaml

protected async override void LoadState(Object navigationParameter,


Dictionary<String, Object> pageState)
{
this.DefaultViewModel["Groups"] = SampleDataSource.AllGroups;

//
await SampleDataSource.AddGroupForFeedAsync(
"http://blogs.msdn.com/b/mikcher/rss.aspx");
await SampleDataSource.AddGroupForFeedAsync(
"http://blogs.msdn.com/b/stasus/rss.aspx");
await SampleDataSource.AddGroupForFeedAsync(
"http://blogs.msdn.com/b/kichinsky/rss.aspx");
}
RSS- Grid App 93

, . , -
, Grid App, .
. , . 7.1. -
GroupDetailPage.xaml (. 7.3).
- .
ItemDetailPage.xaml (. 7.4).

. 7.3. GroupDetailPage.xaml

. 7.4. ItemDetailPage.xaml
94 7

ItemDetailPage.xaml HTML-
. , . . HTML- -
. . -
WebView, , -
HTML-. HTML-
.
, ,

.


, -
1.

LayoutAwarePage.
DefaultViewModel, -
(Dependency Property) DefaultViewModelProperty ( 7.7).

7.7. DefaultViewModel

public class LayoutAwarePage : Page


{
public static readonly DependencyProperty DefaultViewModelProperty =
DependencyProperty.Register("DefaultViewModel",
typeof(IObservableMap<String, Object>),
typeof(LayoutAwarePage), null);

...

protected IObservableMap<String, Object> DefaultViewModel


{
get
{
return this.GetValue(DefaultViewModelProperty)
as IObservableMap<String, Object>;
}

set
{
this.SetValue(DefaultViewModelProperty, value);
}
}

...
}
RSS- Grid App 95

DefaultViewModel " ".


Groups
DefaultViewModel ( 7.8).

7.8. Groups DefaultViewModel

this.DefaultViewModel["Groups"] = SampleDataSource.AllGroups;

XAML- GroupedItemsPage.xaml DefaultViewModel -


( 7.9).

7.9.

<common:LayoutAwarePage
x:Name="pageRoot"
x:Class="RssApp.GroupedItemsPage"
DataContext="{Binding DefaultViewModel,
RelativeSource={RelativeSource Self}}"
...
mc:Ignorable="d">

, " ",
. CollectionViewSource,

, .
CollectionViewSource Groups DefaultViewModel
( 7.10).

7.10. CollectionViewSource

<Page.Resources>
<CollectionViewSource
x:Name="groupedItemsViewSource"
Source="{Binding Groups}"
IsSourceGrouped="true"
ItemsPath="TopItems"/>
</Page.Resources>

GridView, -
( 7.11). GridView -
. -
, . 7.1.
96 7

7.11. GroupedItemsPage.xaml

<common:LayoutAwarePage
x:Name="pageRoot"
x:Class="RssApp.GroupedItemsPage"
DataContext="{Binding DefaultViewModel,
RelativeSource={RelativeSource Self}}"
...
mc:Ignorable="d">

<Page.Resources>
<CollectionViewSource
x:Name="groupedItemsViewSource"
Source="{Binding Groups}"
IsSourceGrouped="true"
ItemsPath="TopItems"/>
</Page.Resources>

<Grid Style="{StaticResource LayoutRootStyle}">


<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Grouped Items"
Grid.RowSpan="2" Padding="116,137,40,46"
ItemsSource=
"{Binding Source={StaticResource groupedItemsViewSource}}"
ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
SelectionMode="None" IsSwipeEnabled="false"
IsItemClickEnabled="True" ItemClick="ItemView_ItemClick">

<GridView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
...
</DataTemplate>
</GroupStyle.HeaderTemplate>
RSS- Grid App 97

<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid Orientation="Vertical"
Margin="0,0,80,0"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</GridView.GroupStyle>
</GridView>

...

</Grid>
</common:LayoutAwarePage>

RSS- Grid App.


SampleDataSource ,
RSS-.
. GroupedItemsPage.xaml
GridView,
.
Taa8


GridView, ListView FlipView
Windows Store-
GridView ListView, -
, ItemsControl -
. GridView -
, ListView ( ).
, , . .
GridView
(. . 7.1). GridView , -
. , GridView -
. . 8.1 -
GridView .

. 8.1. GridView
GridView, ListView FlipView 99

. 8.2
ListView, ,
GridView . 8.1.
GridView ListView

.
GridView ,
ListView (Snapped).
ListView
GridView,

, , -
.

. 8.2.
ListView

GridView
GridView.
Blank App ControlsApp.
MainPage.xaml GridView
gvMain ( 8.1).

8.1. GridView

<Page
...
>
100 8

<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<TextBlock Text="Controls App" Margin="120,0,30,40"


Style="{StaticResource PageHeaderTextStyle}"/>

<GridView x:Name="gvMain" Grid.Row="1" Padding="116,37,40,46">

</GridView>
</Grid>
</Page>

, GridView. -
Person,
, : FirstName, LastName Age
( 8.2).

8.2. Person

public class Person


{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
}

MainPage.xaml Person,
ObservableCollection<T>. -
, (List<T>),
. -
, -
, ListView GridView, -
-
. ObservableCollection<T> ,
.
, . .
GridView. ,
.
, ItemsControl,
(Items) . , -
Items ( 8.3).
GridView, ListView FlipView 101

8.3. Items

gvMain.Items.Add(
new Person { LastName = "", FirstName = "", Age = 31 });


GridView ItemsSource (-
8.4).


7 ItemsSource
XAML-:
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"

8.4. GridView

public sealed partial class MainPage : Page


{
private ObservableCollection<Person> _persons;

public MainPage()
{
this.InitializeComponent();

_persons = new ObservableCollection<Person>();

_persons.Add(new Person { LastName = "",


FirstName = "", Age = 31 });
_persons.Add(new Person { LastName = "",
FirstName = "", Age = 18 });
...

_persons.Add(new Person { LastName = "",


FirstName = "", Age = 24 });

gvMain.ItemsSource = _persons;
}
}

, .
_persons Person, .
. GridView, ,
(. 8.3).
ToString Person.
, .
"ControlsApp.Person".
102 8

. 8.3. GridView

GridView,
(ItemTemplate). -
Avatar.png,
. , -
7. ( 8.5).
160160 .

8.5.

<GridView x:Name="gvMain" Grid.Row="1" Padding="116,37,40,46">


<GridView.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Left" Width="160" Height="160">
<Border Background="{StaticResource
GridView, ListView FlipView 103

ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="/Assets/Avatar.png"
Stretch="UniformToFill"/>
</Border>
<StackPanel VerticalAlignment="Bottom"
Background="{StaticResource
ListViewItemOverlayBackgroundThemeBrush}">

<TextBlock Text="{Binding FirstName}"


Foreground="{StaticResource
ListViewItemOverlayForegroundThemeBrush}"
Style="{StaticResource TitleTextStyle}"
Margin="15,0,15,0"/>

<TextBlock Text="{Binding LastName}"


Foreground="{StaticResource
ListViewItemOverlayForegroundThemeBrush}"
Style="{StaticResource TitleTextStyle}"
Margin="15,0,15,0"/>

<TextBlock Text="{Binding Age}"


Foreground="{StaticResource
ListViewItemOverlaySecondaryForegroundThemeBrush}"
Style="{StaticResource CaptionTextStyle}"
TextWrapping="NoWrap" Margin="15,0,15,10"/>

</StackPanel>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>

-
Person.
. GridView -
(. 8.4). ,
, GridView
, .
, GridView
.
. 7 -
, . ,
.
, : , .
PersonGroup ( 8.6).
104 8

. 8.4.

8.6. PersonGroup

public class PersonGroup


{
public string GroupName { get; set; }
public ObservableCollection<Person> Persons { get; set; }

public PersonGroup()
{
Persons = new ObservableCollection<Person>();
}
}

GroupName,
Persons.
GridView CollectionViewSource.
( 8.7).

8.7. CollectionViewSource

<Page
...
>
GridView, ListView FlipView 105

<Page.Resources>
<CollectionViewSource
x:Name="cvsMain"
IsSourceGrouped="true"
ItemsPath="Persons"/>
</Page.Resources>
...

IsSourceGrouped true, . .
, ItemsPath Persons,
Persons PersonGroup .
CollectionViewSource GridView ( 8.8).

8.8. CollectionViewSource GridView

<GridView x:Name="gvMain" Grid.Row="1" Padding="116,37,40,46"


ItemsSource="{Binding Source={StaticResource cvsMain}}">

CollectionViewSource. -
( 8.9).

8.9.

public sealed partial class MainPage : Page


{
private ObservableCollection<PersonGroup> _groups;

public MainPage()
{
this.InitializeComponent();

_groups = new ObservableCollection<PersonGroup>();

var developers = new PersonGroup { GroupName = "" };


var designers = new PersonGroup { GroupName = "" };
var managers = new PersonGroup { GroupName = "" };

_groups.Add(developers);
_groups.Add(designers);
_groups.Add(managers);

developers.Persons.Add(new Person { LastName = "",


FirstName = "", Age = 31 });
...
managers.Persons.Add(new Person { LastName = "",
FirstName = "", Age = 23 });
106 8

cvsMain.Source = _groups;
}
}

, (. . 8.4).

( 8.10), , -
. -
.
.

8.10.

<GridView x:Name="gvMain" Grid.Row="1" Padding="116,37,40,46"


ItemsSource="{Binding Source={StaticResource cvsMain}}">
...
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="1,0,0,6">
<Button
Style="{StaticResource TextPrimaryButtonStyle}" >
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding GroupName}"
Margin="3,-7,10,10"
Style="{StaticResource GroupHeaderTextStyle}" />
<TextBlock Text="{StaticResource ChevronGlyph}"
FontFamily="Segoe UI Symbol"
Margin="0,-7,0,10"
Style="{StaticResource GroupHeaderTextStyle}"/>
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</GridView.GroupStyle>
</GridView>

. , -
, , (. 8.5).
-, .
. -, -
.
,
GridView, ListView FlipView 107

(GroupStyle.Panel). -
VariableSizedWrapGrid.
, ,
GridView ( 8.11). ,
( ),
80 (Margin="0,0,80,0").

. 8.5.

8.11.

<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
...
</DataTemplate>
</GroupStyle.HeaderTemplate>
108 8

<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid Orientation="Vertical"
Margin="0,0,80,0"
ItemWidth="160" ItemHeight="160"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</GridView.GroupStyle>

VariableSizedWrapGrid (),
160160 (ItemWidth="160" ItemHeight="160").
,
(. 8.5). ,
.
(
GridView). , , ,
, . -
VirtualizingStackPanel ,
( -
) ( 8.12).


,
.


VariableSizedWrapGrid.

8.12. GridView

<GridView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>

. , (. 8.6).
VirtualizingStackPanel
(. 8.7).
. 8.7 , , -
. , , -
, ,
.
GridView, ListView FlipView 109

. 8.6.

. 8.7.
GridView
110 8


GridView
, GridView -
VariableSizedWrapGrid ( , -
). 160160 .
,
320 .
Person HorizontalSize VerticalSize
, ( 8.13). -
, .

8.13. HorizontalSize VerticalSize

public class Person


{
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

private int _horizontalSize = 1;


public int HorizontalSize
{
get { return _horizontalSize; }
set { _horizontalSize = value; }
}

private int _verticalSize = 1;


public int VerticalSize
{
get { return _verticalSize; }
set { _verticalSize = value; }
}
}

Person
( 8.14).

8.14. Person

developers.Persons.Add(new Person { LastName = "",


FirstName = "", Age = 31, HorizontalSize = 2, VerticalSize = 2 });
...
designers.Persons.Add(new Person { LastName = "",
FirstName = "", Age = 24, HorizontalSize = 2, VerticalSize = 1 });
GridView, ListView FlipView 111

designers.Persons.Add(new Person { LastName = "",


FirstName = "", Age = 42, HorizontalSize = 2, VerticalSize = 1 });
...
designers.Persons.Add(new Person { LastName = "",
FirstName = "", Age = 27, HorizontalSize = 1, VerticalSize = 2 });

.
GridView
, GridView.
PrepareContainerForItemOverride,
( -
). VariableGridView ( 8.15).

8.15. VariableGridView

public class VariableGridView : GridView


{
protected override void PrepareContainerForItemOverride(
DependencyObject element, object item)
{
var personItem = item as Person;

if (personItem != null)
{
element.SetValue(VariableSizedWrapGrid.ColumnSpanProperty,
personItem.HorizontalSize);
element.SetValue(VariableSizedWrapGrid.RowSpanProperty,
personItem.VerticalSize);
}

base.PrepareContainerForItemOverride(element, item);
}
}

VariableSizedWrapGrid.ColumnSpanProperty
VariableSizedWrapGrid.RowSpanProperty -
, Person.
GridView
MainPage.xaml VariableGridView ( 8.16).

8.16. GridView VariableGridView

<Page
x:Class="ControlsApp.MainPage"
...
112 8

xmlns:local="using:ControlsApp"
...
>

<Page.Resources>
...
</Page.Resources>

<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<TextBlock Text="Controls App" Margin="120,0,30,40"


Style="{StaticResource PageHeaderTextStyle}"/>

<local:VariableGridView x:Name="gvMain"
Grid.Row="1" Padding="116,37,40,46"
ItemsSource="{Binding Source={StaticResource cvsMain}}">
...
</local:VariableGridView>
</Grid>
</Page>

(. 8.8).

. 8.8. GridView
GridView, ListView FlipView 113

,
. ,
25601440 -
(. 8.9).

. 8.9. 25601440

.
( ).
VariableSizedWrapGrid
MaximumRowsOrColumns ( 8.17).

8.17. MaximumRowsOrColumns

<GroupStyle.Panel>
<ItemsPanelTemplate>
114 8

<VariableSizedWrapGrid Orientation="Vertical" Margin="0,0,80,0"


ItemWidth="160" ItemHeight="160"
MaximumRowsOrColumns="4"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>


GridView
GridView
Person. GridView , -
- . . -
, - ,
, ( ).
, .
. ,
DataTemplateSelector, .
, -
. , ClassA ClassB,
. -
. 8.18.

8.18.

public class SampleTemplateSelector : DataTemplateSelector


{
protected override DataTemplate SelectTemplateCore(object item,
DependencyObject container)
{
if (item == null) return null;

if (item is ClassA)
{
return (DataTemplate)Application.Current.Resources[
"classATemplate"];
}

if (item is ClassB)
{
return (DataTemplate)Application.Current.Resources[
"classBTemplate"];
}
GridView, ListView FlipView 115

return (DataTemplate)Application.Current.Resources[
"basicTemplate"];
}
}


SampleTemplateSelector, GridView (-
8.19).

8.19. SampleTemplateSelector

<Page
x:Class="ControlsApp.MainPage"
...
xmlns:local="using:ControlsApp"
...
>

<Page.Resources>
...
<local:SampleTemplateSelector x:Key="templateSelector"/>
</Page.Resources>

<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
...
<GridView
ItemTemplateSelector="{StaticResource templateSelector}">

</GridView>
...
</Grid>
</Page>


(Semantic Zoom)
(Semantic Zoom) ,
Windows 8, Windows Store-
.

:
116 8

 ();
 (); , -
.
( ,
), -
<Ctrl>, <+> <> -
<Ctrl>. ,

.
, -
ISemanticZoomInformation. , GridView
ListView .

(. 8.10).

. 8.10.

( ) .
(
Windows-), . -
, (. 8.11).
.
, .
GridView, ListView FlipView 117

. 8.11.

, -
.

SemanticZoom, ZoomedInView -
ZoomedInView ( 8.20).

8.20. SemanticZoom

<SemanticZoom>
<SemanticZoom.ZoomedInView>
<!-- -->
</SemanticZoom.ZoomedInView>
<SemanticZoom.ZoomedOutView>
<!-- -->
</SemanticZoom.ZoomedOutView>
</SemanticZoom>

GridView .
GridView
. GridView
gvZoomedOut ( 8.21), . .
.
118 8

8.21.

<SemanticZoom x:Name="semanticZoom" Grid.Row="1">


<SemanticZoom.ZoomedInView>
<local:VariableGridView x:Name="gvMain" Padding="116,37,40,46"
ItemsSource="{Binding Source={StaticResource cvsMain}}">
...
</local:VariableGridView >
</SemanticZoom.ZoomedInView>
<SemanticZoom.ZoomedOutView>
<GridView x:Name="gvZoomedOut" SelectionMode="None"
Padding="116,37,40,46">
<GridView.ItemTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Group.GroupName}"
Style="{StaticResource GroupHeaderTextStyle}"/>
</DataTemplate>
</GridView.ItemTemplate>
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<WrapGrid ItemWidth="200" ItemHeight="200"
MaximumRowsOrColumns="1"
VerticalChildrenAlignment="Center" />
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="Margin" Value="4" />
<Setter Property="Padding" Value="10" />
<Setter Property="BorderBrush" Value="Gray" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="HorizontalContentAlignment"
Value="Center" />
<Setter Property="VerticalContentAlignment"
Value="Center" />
</Style>
</GridView.ItemContainerStyle>
</GridView>
</SemanticZoom.ZoomedOutView>
</SemanticZoom>


GridView ( ).
CollectionViewSource cvsMain.
, .
MainPage gvZoomedOut ( 8.22).
GridView, ListView FlipView 119

8.22. gvZoomedOut

public MainPage()
{
this.InitializeComponent();

...

cvsMain.Source = _groups;
gvZoomedOut.ItemsSource = cvsMain.View.CollectionGroups;
}

, . -
. ""
(. 8.12).

. 8.12.

: , , -
( <Ctrl>)
.
(. 8.13).
, -
.


, . . .
, , , -
.
. -
. -
.
120 8

. 8.13.

ListView
ListView , GridView.
ListView, ,
GridView. :
( 8.23).

8.23. ListView

<ListView x:Name="lvMain" Grid.Row="1"


Margin="0,-10,0,0" Padding="10,0,0,60" Width="320"
ItemsSource="{Binding Source={StaticResource cvsMain}}">
<ListView.ItemTemplate>
<DataTemplate>
<Grid Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Border Background="{StaticResource
ListViewItemPlaceholderBackgroundThemeBrush}"
Width="60" Height="60">
<Image Source="/Assets/Avatar.png"
Stretch="UniformToFill"/>
</Border>
GridView, ListView FlipView 121

<StackPanel Grid.Column="1" Margin="10,0,0,0">


<TextBlock Text="{Binding FirstName}" MaxHeight="40"/>
Style="{StaticResource ItemTextStyle}"
<TextBlock Text="{Binding LastName}"
Style="{StaticResource CaptionTextStyle}"
TextWrapping="NoWrap"/>
<TextBlock Text="{Binding Age}"
Style="{StaticResource CaptionTextStyle}"
TextWrapping="NoWrap"/>
</StackPanel>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="7,7,0,0">
<Button
Style="{StaticResource TextPrimaryButtonStyle}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding GroupName}"
Margin="3,-7,10,10"
Style="{StaticResource GroupHeaderTextStyle}" />
<TextBlock Text="{StaticResource ChevronGlyph}"
FontFamily="Segoe UI Symbol" Margin="0,-7,0,10"
Style="{StaticResource GroupHeaderTextStyle}"/>
</StackPanel>
</Button>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
</GroupStyle>
</ListView.GroupStyle>
</ListView>

ListView . 8.14.
ListView GridView. -
SelectionMode,
. 8.1.

8.1. SelectionMode


None
Single
122 8

8.1 ()

Multiple

Extended ,
, , ,
<Shift>,

. 8.14.
ListView
GridView, ListView FlipView 123

FlipView
, -
, FlipView .
.
FlipView , GridView ListView ItemsControl,
-
. FlipView
, -
.
FlipView
- . FlipView -
-.
FlipView People.
, GridView ( 8.24).

8.24. FlipView

<FlipView ItemsSource="{Binding Source={StaticResource cvsMain}}" Grid.Row="1"


Width="250" Height="250">
<FlipView.ItemTemplate>
<!-- -->
</FlipView.ItemTemplate>
</FlipView>

FlipView
(. 8.15). . 8.15 -
.

FlipView . FlipView
.

. 8.15. FlipView
124 8

GridView, ListView FlipView.


, -
.
GridView ListView. , ,
Grid App, 7.
,
:
(Snapped).
Taa9

1, Windows Store-
( . 9.1):
 (Full Screen);
 ( c) (Snapped).
320 ;

(Filled).
,
1366768 . , Windows Store-
.

.
, , -
, -
.

. 9.1.
126 9

,
8.


, , -
. - ,
320 ,
. .
, GridView, -
ListView.
, .
GridView SemanticZoom (-
9.1). , 8.

9.1. MainPage.xaml

<Page
...
>
...
<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>

<TextBlock Text="Controls App" Margin="120,0,30,40"


Style="{StaticResource PageHeaderTextStyle}"/>

<SemanticZoom x:Name="semanticZoom" Grid.Row="1">


<SemanticZoom.ZoomedInView>
<local:VariableGridView x:Name="gvMain"
Padding="116,37,40,46"
ItemsSource="{Binding Source={StaticResource cvsMain}}">
...
</local:VariableGridView >
</SemanticZoom.ZoomedInView>
<SemanticZoom.ZoomedOutView>
<GridView x:Name="gvZoomedOut"
SelectionMode="None" Padding="116,37,40,46">
...
</GridView>
</SemanticZoom.ZoomedOutView>
</SemanticZoom>
127

<ListView x:Name="lvMain" Grid.Row="1" Visibility="Collapsed"


Margin="0,-10,0,0" Padding="10,0,0,60"
Width="320" SelectionMode="Extended"
ItemsSource="{Binding Source={StaticResource cvsMain}}">
...
</ListView>
</Grid>
</Page>

ListView , . . Visibility
Collapsed.
ListView lvMain -
SemanticZoom semanticZoom.
.

Value ApplicationView, :
 Snapped
 Filled
 FullScreenLandscape
 FullScreenPortrait
, ,
. ,
, 9.2.

9.2.

switch (ApplicationView.Value)
{
case ApplicationViewState.Snapped:
{
}
break;
case ApplicationViewState.Filled:
{
}
break;
case ApplicationViewState.FullScreenLandscape:
{
}
break;

case ApplicationViewState.FullScreenPortrait:
{
}
break;
}
128 9

. -
.
( Window.Current.SizeChanged). , -
, ,
. -
, .

( 9.3).

9.3.

public sealed partial class MainPage : Page


{
private ObservableCollection<PersonGroup> _groups;

public MainPage()
{
this.InitializeComponent();

...

Window.Current.SizeChanged += Current_SizeChanged;
}

void Current_SizeChanged(object sender,


WindowSizeChangedEventArgs e)
{
if (ApplicationView.Value == ApplicationViewState.Snapped)
{
semanticZoom.Visibility = Visibility.Collapsed;
lvMain.Visibility = Visibility.Visible;
}
else
{
semanticZoom.Visibility = Visibility.Visible;
lvMain.Visibility = Visibility.Collapsed;
}
}
}

. -
- (. 9.2).
(Bing
Weather), Filled.
Visual
Studio. Device.
View (. 9.3).
129

. 9.2.
130 9

. 9.3.

Visual State Manager


, , Grid
App, , , Basic Page,
LayoutAwarePage. -
, . ,
LayoutAwarePage, , -
.
RSS- 7 GroupedItemsPage.xaml
, -
( 9.4).

9.4.

<common:LayoutAwarePage
... >
...
<Grid Style="{StaticResource LayoutRootStyle}">
...
<GridView x:Name="itemGridView"
... >
...
</GridView>
131

<ListView x:Name="itemListView"
... >
...
</ListView>

<Grid>
...
<Button x:Name="backButton" Click="GoBack"
IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}"
Style="{StaticResource BackButtonStyle}"/>
<TextBlock x:Name="pageTitle" Text="{StaticResource AppName}"
Grid.Column="1" IsHitTestVisible="false"
Style="{StaticResource PageHeaderTextStyle}"/>
</Grid>

<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ApplicationViewStates">
<VisualState x:Name="FullScreenLandscape"/>
<VisualState x:Name="Filled"/>
<VisualState x:Name="FullScreenPortrait">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="backButton"
Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource PortraitBackButtonStyle}"/>
</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="itemGridView"
Storyboard.TargetProperty="Padding">
<DiscreteObjectKeyFrame KeyTime="0"
Value="96,137,10,56"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Snapped">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="backButton"
Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource SnappedBackButtonStyle}"/>
</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="pageTitle"
132 9

Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource
SnappedPageHeaderTextStyle}"/>
</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="itemListView"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0"
Value="Visible"/>
</ObjectAnimationUsingKeyFrames>

<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="itemGridView"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0"
Value="Collapsed"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</common:LayoutAwarePage>

Visual State
Manager (VSM, ). -
XAML-. ,
, VSM .
LayoutAwarePage
VSM , -
. VSM .
VSM , LayoutAwarePage,
VSM LayoutAwarePage.
LayoutAwarePage
VisualStateManager.GoToState.
Device Visual Studio -
.
, VSM ,
. -
(Storyboard),
. 9.5
.
133

9.5.

<VisualState x:Name="Snapped">
<Storyboard>
...
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="itemListView"
Storyboard.TargetProperty="Visibility">
<DiscreteObjectKeyFrame KeyTime="0" Value="Visible"/>
</ObjectAnimationUsingKeyFrames>
...
</Storyboard>
</VisualState>

9.5 ListView
itemListView. Visibility,
Visible.
(
) , . . VSM ,
.
FullScreenPortrait ListView -
.
Visual State Manager
, ,
, , -
. Visual State Manager ,
.



,
(PPI, Pixels Per Inch ). , 27--
25601440.
10- , 1024768, -
.
25601440, 1024768, , -
,
(PPI
, ).
Windows 8 Windows Store- , -
-
134 9

PPI. Windows ,
PPI
. . -
.
:
 100% ;
 140% 19201080 PPI 174;
 180% 25601440 PPI 240.
, , - -
. -
, XAML, -
.


, . , -
.

, PNG
JPEG. .
. -
, -
. -
. -
.
-
.
. ,
:
 logo.scale-100.png 100100;
 logo.scale-140.png 210210;
 logo.scale-180.png 270270.
XAML- ( 9.6).

9.6.

<Image Source="logo.png" Width="100" Height="100"/>

!
, logo.png.
. , -
, .
135

, -
. :
 scale-100\logo.png;
 scale-140\logo.png;
 scale-180\logo.png.
-
. XAML- ,
, .

(Snapped) ,
. ,
, -
.
-
Visual State Manager (VSM). LayoutAwarePage
VSM.
, -
Windows Store- .

.
, .
Taa10


Win-
dows Store-, -
, .
, -
, -
,
. -

Windows.
,
-
: , -
,
.
, -
,
, -
. -
,
.


, Windows Store- ,
. Windows Store-
.
. 137

-. -
-.
, -
, - .
, , -
,
. ,
(Suspended). , .
,
(Terminated). Win-
dows Store- . 10.1.

. 10.1. Windows Store-

. ,
4, -
.
, , -
. , ,
, . .
.

App.xaml.cs. OnLaunched,
OnSuspending ( 10.1). -
, 4.

10.1. App.xaml.cs

protected override void OnLaunched(LaunchActivatedEventArgs args)


{
...
}
138 10

private void OnSuspending(object sender, SuspendingEventArgs e)


{
...
}

.
PreviousExecutionState args
. -
PreviousExecutionState:
 NotRunning -
, (log off),
.
 Running ,
, , , -
(Secondary tile).
 Suspended -
.
 Terminated -
. -
, Suspended,
Terminated.
 ClosedByUser .
OnLaunched .
, , -
OnLaunched.
OnSearchActivated ( 10.2).

10.2. ""

protected override void OnSearchActivated(SearchActivatedEventArgs args) {


...
}

OnSearchActivated ,
, -
"-".

13.

, OnLaunched OnSearchActivated
. -
.
.
. 139


,
Windows Store- ( ),
,
, . -
, , /
, , -
, . . .
, , -
.

/
BackgroundDownloader,
BackgroundUploader. ()
, , (), -
.
HTTP HTTPS ( GET, POST)
() HTTP HTTPS (
POST) . -
.
, ,
.
Windows Store- Blank App
DownloadApp. MainPage.xaml
btnStartDownload tbDownloadProgress ( 10.3).

10.3. MainPage.xaml

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">


<StackPanel>
<Button x:Name="btnStartDownload" Content=" "
Margin="24" Height="42" Width="126"/>
<TextBlock x:Name="tbDownloadProgress" Margin="24"
TextWrapping="Wrap" Text=" "
Style="{StaticResource HeaderTextStyle}"/>
</StackPanel>
</Grid>

btnStartDownload. -
.
, ,
. -
. 10.3.
140 10

10.3.

StorageFile destinationFile = await


ApplicationData.Current.LocalFolder.CreateFileAsync("file.dat");

BackgroundDownloader
( DownloadOperation). -
( 10.3).
, StartAsync. -
10.4.

10.4.

public sealed partial class MainPage : Page


{
private CancellationTokenSource _cancellationTokenSource =
new CancellationTokenSource();

public MainPage()
{
this.InitializeComponent();
}

private async void btnStartDownload_Click(object sender,


RoutedEventArgs e)
{
try
{
//
Uri source = new Uri("http://www._.ru/file.dat");

StorageFile destinationFile = await


ApplicationData.Current.LocalFolder.CreateFileAsync("file.dat");

var downloader = new BackgroundDownloader();


DownloadOperation download = downloader.CreateDownload(source,
destinationFile);

var asyncOperation = download.StartAsync();

var task = asyncOperation.AsTask(


_cancellationTokenSource.Token,
new Progress<DownloadOperation>(DownloadProgress));
}
. 141

catch (Exception ex)


{
//
}
}

private void DownloadProgress(DownloadOperation obj)


{
var progress = (int)(obj.Progress.BytesReceived * 100 /
obj.Progress.TotalBytesToReceive);

tbDownloadProgress.Text = String.Format("{0}% {1}", progress,


obj.ResultFile.Name);
}

StartAsync .
, .
, ,
( 10.5).

10.5. Task

var task = asyncOperation.AsTask(


_cancellationTokenSource.Token,
new Progress<DownloadOperation>(DownloadProgress));

DownloadProgress.

.
, . .
.
AttachToProccesses,
, BackgroundDownloader.GetCurrentDownloadsAsync. -
.

10.6.

public MainPage()
{
this.InitializeComponent();

AttachToProcesses();
}
142 10

private async void AttachToProcesses()


{
try
{
var downloads = await
BackgroundDownloader.GetCurrentDownloadsAsync();

var download = downloads.FirstOrDefault();

if (download != null)
{
var task = download.AttachAsync().AsTask(
_cancellationTokenSource.Token,
new Progress<DownloadOperation>(DownloadProgress));
}
}
catch (Exception ex)
{
//
}
}

-
, .


Windows Store- .

, . -
, -
(, -) (-
, ). -
( )
( ) .
(Assembly, DLL-
). ,
(, . .).
, ,
. , -
, . -
,
WNS (Windows Push Notification Services
Windows). Push- , -
. 143

(
).

, (Lock Screen) .
,
(. 10.2).

. 10.2. ( Windows
http://blogs.msdn.com/b/b8/archive/2012/06/14/building-the-mail-app.aspx)

, ,
( ), , -
, -
.
. ,
. -
,
(. 10.3).
, ,
, .
, -
(. 10.1).
. 10.1 , . ,
, ,
. . ,
144 10

, 2 -
15 . 15
.
(. 10.2).

. 10.3. ,

10.1.

, 2 15

, 1 2

10.2.


ControlChannelTrigger , -
. , ,
, ,
TCP-
. ,

. 145

10.2 ()


MaintenanceTrigger
TimeTrigger . TimeTrigger ,
.
MaintenanceTrigger ,
.
. -

( 15 .), .
,

PushNotificationTrigger , Push- Raw
( 11). -

SystemEventTrigger .
,

. 10.3 ,
SystemEventTrigger. , , -
, .

10.3. SystemEventTrigger


InternetAvailable
NetworkStateChange . ,
Wi-Fi 3G
OnlineIdConnectedStateChange ,
ServicingComplete
LockScreenApplicationAdded
LockScreenApplicationRemoved
ControlChannelReset*
SessionConnected*
SmsReceived -
TimeZoneChange , ,

UserAway*
UserPresent*

. . -
, .
146 10

, . -
InternetAvailable.
. 10.4.

10.4.

InternetAvailable
InternetNotAvailable
SessionConnected
SessionDisconnected
UserNotPresent
UserPresent


, . -
, -
IBackgroundTask.
Blank App TasksApp.
, (solution) -
Windows Runtime Component. Solution Explorer -
Solution TasksApp (1 project) Add | New
Project... Windows
Runtime Component TasksComponent.
Windows Store- .
References Add
Reference... TasksComponent.
Solution Explorer
. 10.4.
, , -
, -
.
TasksComponent (-
10.7).

10.7.

public sealed class SampleBackgroundTask : IBackgroundTask


{
public void Run(IBackgroundTaskInstance taskInstance)
. 147

{
var deferral = taskInstance.GetDeferral();

try
{
//
}
finally
{
deferral.Complete();
}
}
}

. 10.4.
Solution Explorer

SampleBackgroundTask
. Package.appxmanifest
Declarations Background Tasks.
System Event, (Entry point) -
TasksComponent.SampleBackgroundTask (. 10.5).
-
. MainPage.xaml , -
.
BackgroundTaskBuilder. -
. , -
( 10.8).
148 10

. 10.5.

10.8.

private void ButtonRegisterClick(object sender, RoutedEventArgs e)


{
var timerTrigger = new
SystemTrigger(SystemTriggerType.TimeZoneChange, false);

var builder = new BackgroundTaskBuilder();

builder.Name = "SampleBackgroundTask";
builder.TaskEntryPoint = "TasksComponent.SampleBackgroundTask";
builder.SetTrigger(timerTrigger);

BackgroundTaskRegistration task = builder.Register();


}

SystemTrigger ,
. (TimeZoneChange).
. 149

BackgroundTaskBuilder -
, (-
10.9).

10.9.

private void ButtonRegisterClick(object sender, RoutedEventArgs e)


{
var timerTrigger = new
SystemTrigger(SystemTriggerType.TimeZoneChange, false);

var builder = new BackgroundTaskBuilder();

builder.Name = "SampleBackgroundTask";
builder.TaskEntryPoint = "TasksComponent.SampleBackgroundTask";
builder.SetTrigger(timerTrigger);

IBackgroundCondition condition = new


SystemCondition(SystemConditionType.InternetAvailable);
builder.AddCondition(condition);

BackgroundTaskRegistration task = builder.Register();


}

Completed BackgroundTaskRegistration -
.
,
( 10.10).

10.10.

private void ButtonUnRegisterClick(object sender, RoutedEventArgs e)


{
foreach (var task in BackgroundTaskRegistration.AllTasks)
{
task.Value.Unregister(true);
}
}

, ,
. . -
. , -
Visual Studio
Debug Location (. 10.6). ,
(Suspend),
(Resume), (Suspend
150 10

. 10.6. Debug Location

and shutdown),
SampleBackgroundTask.
Debug Location , VIEW |
Toolbars | Debug Location.

Windows Store-, -
Windows-.
Windows Store- , -
.
/ BackgroundDownloader
BackgroundUploader . ,
, , -,
( ).
,
. -
. , -
,
.
Taa11

? ,
, -
- -
. , -
, .
.
(Toast Notification).
(Tiles) .

, (Push-
).
,
Push-. 12.


-
.
. : -
, -
, - .
:
 7
.

25 .
152 11

.
.
, (. 11.1).

11.1.

ToastImageAndText01

ToastImageAndText02

ToastImageAndText03

ToastImageAndText04

ToastText01

ToastText02

ToastText03

ToastText04

, -
, . 11.1.
153

. 11.1.

(, Push-
), -
. Application UI , Notifications
Yes Toast capable (. 11.2).
XML-,
. ToastText01
( 11.1).

11.1. XML- ToastText01

<toast>
<visual>
<binding template="ToastText01">
<text id="1">
</text>
</binding>
</visual>
</toast>

XML- ToastNotification (-
) ToastNotifier (-
11.2).
154 11

. 11.2.

11.2.

var xml = @"<toast>


<visual>
<binding template=""ToastText01"">
<text id=""1""> </text>
</binding>
</visual>
</toast>";
155

var xmlDocument = new XmlDocument();


xmlDocument.LoadXml(xml);

var toast = new ToastNotification(xmlDocument);

ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();


notifier.Show(toast);

, , . .
.
, 10
( 11.3).

11.3.

var xml = @"<toast>


<visual>
<binding template=""ToastText01"">
<text id=""1""> </text>
</binding>
</visual>
</toast>";

var xmlDocument = new XmlDocument();


xmlDocument.LoadXml(xml);

var toast = new ScheduledToastNotification(xmlDocument,


DateTimeOffset.Now.AddSeconds(10));

ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();


notifier.AddToSchedule(toast);

.
,
, , , . .
( ), -
. ,
, , -
(Push-). -
, (, , -
). -
.

Push-
Push- (Push Notification)
( ). "" (push) ,
(, pull) . Windows-
156 11

-
. Windows Store-, ,
, . Push-
.
. Push- -
.
, -
. Push- -
Windows (WNS, Windows Push Notification Services).
( ) -
WNS, ,
,
.
Push- Windows Store-
,
. ,
, WNS -
. WNS
.
Push-:
 Toast . ,
;
 Tile Badge , .
12;
 Raw . Raw-
, "" -
, -
. Raw- ,
.
Raw- , , Raw-
, , -
.

WNS-.

Windows Store

WNS, ,
.
Windows Store, -
. ,
.
157

MSDN :
http://msdn.microsoft.com/ru-ru/library/windows/apps/hh465407.aspx
, "" , -
Windows Store, ,
, Windows Store.
""
Windows Store.
Store | Associate with the Store Visual Studio Express
Project | Store | Associate with the Store Visual Studio.
, -
:
 SID (Package Security Identifier / )
ms-app://s-1-15-2-347940726-2465832990-910876698-369105280-2399447978-
997722633-4228783870.

 Client secret / ( 1)
-a0o4J2-drcAxBUKeBA7cT06orFATHJw.

. ,
Push- .
Windows Store- .
,
, -
. -
.
- . , -
,
. WNS
, .
, ,
.

Push-
Windows Store -
, Push-.
Push- .
, -
. Windows Store- -
URI, ( ) -
.

PushNotificationChannelManager ( 11.4).
158 11

11.4. URI

PushNotificationChannel channel = await


PushNotificationChannelManager.CreatePushNotificationChannelForApplicationAsync
();
var uri = channel.Uri;

URI:
https://db3.notify.windows.com/?token=AgUAAAC0wm%2frjhZ0ciivfeaM%2bn0c2vh8%2fuJ
2NFN6PdwAzkv8KkWrwDvw7qEix%2fzkZsvbQJYt5mR45K7MP2ExP%2fSF4WF8zUuuzlDH6UYoMnwj2A
KA4wadN%2bc9qGUEBYvBcVO4Qt0%3d


URI .
.

URI
PushNotificationChannel, Push--
, .
.
, C#.
. -
, , , ASP.NET MVC, PHP,
Python, Ruby, Java, node.js . .
, ,
XML-. -
11.5.

11.5.

static void Main(string[] args)


{
var secret = "-a0o4J2-drcAxBUKeBA7cT06orFATHJw";
var sid = "ms-app://s-1-15-2-347940726-2465832990-...";
var url = "https://db3.notify.windows.com/?token=...";

var xml = @"<toast>


<visual>
<binding template=""ToastText01"">
<text id=""1"">Push-</text>
</binding>
</visual>
</toast>";

var status = PostToWns(secret, sid, url, xml, "wns/toast");


Console.WriteLine(status);
}
159

sid secret , -
Windows Store, url , . -
, sid secret
, , , , -
, -
.
PostToWns, .
,
WNS-. WNS-
OAuthToken ( 11.6).

11.6.
WNS-

[DataContract]
public class OAuthToken
{
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
[DataMember(Name = "token_type")]
public string TokenType { get; set; }
}


System.Runtime.Serialization.dll.

WNS- (-
11.7).

11.7. WNS-

private static string PostToWns(string secret, string sid,


string uri, string xml, string type)
{
try
{
var accessToken = GetAccessToken(secret, sid);
var contentInBytes = Encoding.UTF8.GetBytes(xml);

var request = WebRequest.Create(uri) as HttpWebRequest;


request.Method = "POST";
request.Headers.Add("X-WNS-Type", type);
request.Headers.Add("Authorization",
String.Format("Bearer {0}", accessToken.AccessToken));
160 11

using (var requestStream = request.GetRequestStream())


{
requestStream.Write(contentInBytes, 0,
contentInBytes.Length);
}

using (var webResponse = (HttpWebResponse)request.GetResponse())


{
return webResponse.StatusCode.ToString();
}
}
catch (WebException webException)
{
var exceptionDetails =
webException.Response.Headers["WWW-Authenticate"];
if (exceptionDetails.Contains("Token expired"))
{
GetAccessToken(secret, sid);
return PostToWns(uri, xml, secret, sid, type);
}

return "EXCEPTION: " + webException.Message;


}
catch (Exception ex)
{
return "EXCEPTION: " + ex.Message;
}
}

private static OAuthToken GetAccessToken(string secret, string sid)


{
var urlEncodedSecret = HttpUtility.UrlEncode(secret);
var urlEncodedSid = HttpUtility.UrlEncode(sid);

var body = String.Format(


"grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.win
dows.com", urlEncodedSid, urlEncodedSecret);

string response;
using (var client = new WebClient())
{
client.Headers.Add("Content-Type",
"application/x-www-form-urlencoded");
response = client.UploadString(
"https://login.live.com/accesstoken.srf", body);
}

return GetOAuthTokenFromJson(response);
}
161

private static OAuthToken GetOAuthTokenFromJson(string jsonString)


{
using (var ms = new
MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
{
var ser = new DataContractJsonSerializer(typeof(OAuthToken));
var oAuthToken = (OAuthToken)ser.ReadObject(ms);
return oAuthToken;
}
}


System.Web.dll. -
WNS , . .
.

, . -
, XML-,
, .
PostToWns:
 wns/toast ;
 wns/badge ;
 wns/tile ;
 wns/raw Raw-.
" " WNS-. -
.NET, -
, WnsRecipe,
, .

.
-
.
.
, -
. ,
.
Windows Store--
, ,
( ""). -
WNS. WNS
, -
.
Taa12

""

, Windows 8 -
.
, (Tiles) . -
"" (Live Tile)
-
.
, (Secondary Tiles), -
, -
. , -
, , -
"" "", .


. ,
, , .


Windows 8 : 150150
(Square) 310150 (Wide) (. 12.1).
Windows Store-
(Package.appxmanifes) Tile
. ,
310150 . -
-
-
.
"" 163

. 12.1.

( -
, ), -
,
, , -
(. 12.2).
#464646.

. 12.2.

""
, Windows 8 "" ,
.
46 . -
MSDN. 10 36 .
, ,
. , -
( ). -
,
.
164 12

. 12.3.

. 12.4.
"" 165

. 12.3,
. 12.4.
. 12.1 12.2 -
.
, .
, , .

12.1.



(/)

TileSquareBlock, TileSquareImage TileSquarePeekImageAndText01


TileSquareText01, TileSquarePeekImageAndText02
TileSquareText02, TileSquarePeekImageAndText03
TileSquareText03, TileSquarePeekImageAndText04
TileSquareText04,

12.2.

TileWideBlockAndText01 TileWideImage
TileWideBlockAndText02 TileWideImageCollection TileWideImageAndText01
TileWideText01 TileWideImageAndText02
TileWideText02 TileWideSmallImageAndText01
TileWideText03 TileWideSmallImageAndText02
TileWideText04 TileWideSmallImageAndText03
TileWideText05 TileWideSmallImageAndText04
TileWideText06 TileWideSmallImageAndText05
TileWideText07
TileWideText08 ()
TileWideText09 TileWidePeekImageCollection01
TileWideText10 TileWidePeekImageCollection02
TileWideText11 TileWidePeekImageCollection03
TileWidePeekImageCollection04
TileWidePeekImageCollection05
TileWidePeekImageCollection06
TileWidePeekImageAndText01
TileWidePeekImageAndText02
TileWidePeekImage01
TileWidePeekImage02
TileWidePeekImage03
TileWidePeekImage04
TileWidePeekImage05
TileWidePeekImage06
166 12


Windows Store- -
, . ,
, .
.
, -
, , -
.
XML-, -
, . ,
TileSquareBlock XML- 12.1.

12.1. XML- TileSquareBlock

<tile>
<visual>
<binding template="TileSquareBlock">
<text id="1">Text Field 1</text>
<text id="2">Text Field 2</text>
</binding>
</visual>
</tile>

TileSquareBlock -
. ( 12.2).

12.2.

<tile>
<visual>
<binding template="TileSquareBlock">
<text id="1">25</text>
<text id="2"></text>
</binding>
</visual>
</tile>

XML- () -
. XML-
TileNotification.
TileUpdater ( 12.3).
"" 167

12.3.

var xml = @"<tile>


<visual>
<binding template=""TileSquareBlock"">
<text id=""1"">25</text>
<text id=""2""></text>
</binding>
</visual>
</tile>";

var xmlDocument = new XmlDocument();


xmlDocument.LoadXml(xml);

var notification = new TileNotification(xmlDocument);


TileUpdater updateManager =
TileUpdateManager.CreateTileUpdaterForApplication();
updateManager.Update(notification);

(. -
11) . , , -
, XML-.
-
. 12.5.
, -

( SmallLogo.png).

. 12.5.


168 12

XML- .
, - -
. XML-
TileUpdateManager. XML-
TileSquareBlock ( 12.4).

12.4. XML- TileSquareBlock

var xmlDocument =
TileUpdateManager.GetTemplateContent(TileTemplateType.TileSquareBlock);

var nodes = xmlDocument.GetElementsByTagName("binding").First().ChildNodes;


nodes[0].InnerText = "30";
nodes[1].InnerText = "";

var notification = new TileNotification(xmlDocument);


var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();
updateManager.Update(notification);

: -
, -
.
MSDN NotificationsExtensions, -
. -
:
http://code.msdn.microsoft.com/windowsapps/app-tiles-and-badges-sample-
5fc49148
, -
XML-. NotificationsExtensions -
12.5.

12.5. NotificationsExtensions

ITileSquareBlock tileContent = TileContentFactory.CreateTileSquareBlock();


tileContent.TextBlock.Text = "35";
tileContent.TextSubBlock.Text = "";
TileUpdateManager.CreateTileUpdaterForApplication().
Update(tileContent.CreateNotification());

XML- , . .
-
.
"" 169


.
.
.
, ,
. XML- (-
12.6). TileWideText03.

12.6. XML-

<tile>
<visual>
<binding template="TileSquareBlock">
<text id="1">10</text>
<text id="2"></text>
</binding>
<binding template="TileWideText03">
<text id="1">10 </text>
</binding>
</visual>
</tile>

,
12.3. -
. 12.6.

. 12.6.

170 12


"-
" . ,
. TileWideImage TileSquareImage
( 12.7).

12.7.

<tile>
<visual>
<binding template="TileSquareImage">
<image id="1" src="Assets\SmallLogo.png" alt="alt text"/>
</binding>
<binding template="TileWideImage">
<image id="1" src="Assets\WideLogo.png" alt="alt text"/>
</binding>
</visual>
</tile>

12.7
Windows Store-.
( 12.8).

12.8.

<tile>
<visual>
<binding template="TileSquareImage">
<image id="1" alt="alt text"
src="ms-appx:///Assets/SquareTileLogo.png" />
</binding>
<binding template="TileWideImage">
<image id="1" alt="alt text"
src="ms-appx:///Assets/WideLogo.png" />
</binding>
</visual>
</tile>

,
ms-appdata:///local/. ,
HTTP-, -
.
"" 171


, ,
. ,
.
, -
( 12.9).

12.9.

var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();


updateManager.Clear();

. -
"" 10 ( 12.10).

12.10.

var xml = @"<tile>


...
</tile>";

var xmlDocument = new XmlDocument();


xmlDocument.LoadXml(xml);

var notification = new TileNotification(xmlDocument);


notification.ExpirationTime = DateTimeOffset.Now.AddSeconds(10);

var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();


updateManager.Update(notification);

, 12.10, ,
"" 10 . Windows 8 -
,
. , - ,
, , , -
, , . . .
, 10 ,
12.11.

12.11.

var xml = @"<tile>


...
</tile>";
172 12

var xmlDocument = new XmlDocument();


xmlDocument.LoadXml(xml);

var notification = new TileNotification(xmlDocument);


var scheduledTileNotification = new
ScheduledTileNotification(notification.Content,
DateTimeOffset.Now.AddSeconds(10));

var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();


updateManager.AddToSchedule(scheduledTileNotification);


Windows 8 , ,
.
EnableNotificationQueue TileUpdater
( 12.2).

12.12.

var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();


updateManager.EnableNotificationQueue(true);

,
(-
12.13).

12.13.

var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();


updateManager.Clear();
updateManager.EnableNotificationQueue(true);

for (int i = 1; i <= 5; i++)


{
var xml = @"<tile>
<visual>
<binding template=""TileSquareBlock"">
<text id=""1"">{0}</text>
<text id=""2""></text>
</binding>
"" 173

<binding template=""TileWideText03"">
<text id=""1"">{0} </text>
</binding>
</visual>
</tile>";

var xmlDocument = new XmlDocument();


xmlDocument.LoadXml(String.Format(xml, i * 10));

var notification = new TileNotification(xmlDocument);


updateManager.Update(notification);
}

, -
. updateManager.Clear ,

,
.
,
,
.


( ). -
1
99 (, ), 100,
"99+" (, -
).
BadgeUpdateManager,
TileUpdateManager .
. , -
, XML-. 12.14 -
42 (. 12.7).

. 12.7.
174 12

12.14.

var xmlDocument = new XmlDocument();


xmlDocument.LoadXml(@"<badge value=""42""/>");
var badgeNotification = new BadgeNotification(xmlDocument);
var updateManager = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
updateManager.Update(badgeNotification);

42 -
, "" .
, XML-
42 . , attention
( 12.15).

12.15.

xmlDocument.LoadXml(@"<badge value=""attention""/>"));

. 12.8.

. 12.8.

. 12.3.

12.3.

XML-

activity <badge value="activity"/>

alert <badge value="alert"/>

available <badge value="available"/>

away <badge value="away"/>


"" 175

12.3 ()

XML-

busy <badge value="busy"/>

newMessage <badge value="newMessage"/>

paused <badge value="paused"/>

playing <badge value="playing"/>

unavailable <badge value="unavailable"/>

error <badge value="error"/>

attention <badge value="attention"/>



. -
- "".
, . , -
. -
.
. -
, .
. -
:
 Push-;
 .
Push-, 11, , -
, . . -
. -
,
, Push-
, .
, , -
, . XML-
176 12

, -
-
. , , -
.
Push- .
, . . -
. Push- .
XML- , -
. ,
, , .
, XML- 12.6 :
http://foo.ru/TileHandler.ashx.
, (-
), -
( 12.16).

12.16.

var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();

updateManager.StartPeriodicUpdate(new Uri("http://foo.ru/TileHandler.ashx"),
PeriodicUpdateRecurrence.HalfHour);

, , ,
.
. -
( 12.17).

12.17. ,

var updateManager = TileUpdateManager.CreateTileUpdaterForApplication();


updateManager.EnableNotificationQueue(true);

Uri[] uriCollection = new[]


{
new Uri("http://foo.ru/TileHandler1.ashx"),
new Uri("http://foo.ru/TileHandler2.ashx"),
new Uri("http://foo.ru/TileHandler3.ashx"),
new Uri("http://foo.ru/TileHandler4.ashx"),
new Uri("http://foo.ru/TileHandler5.ashx"),
};

updateManager.StartPeriodicUpdateBatch(uriCollection,
PeriodicUpdateRecurrence.HalfHour);
"" 177

. 12.18 -
XML- .

12.18.

var updateManager = BadgeUpdateManager.CreateBadgeUpdaterForApplication();

updateManager.StartPeriodicUpdate(new
Uri("http://foo.ru/TileBadgeHandler.ashx"), PeriodicUpdateRecurrence.HalfHour);


(Secondary Tiles) Windows Store-
-
. ,
,
.
() . ,
, .
( 12.19).

12.19.

private async void Button_Click(object sender, RoutedEventArgs e)


{
SecondaryTile secondaryTile = new SecondaryTile()
{
TileId = "12345",
ShortName = " ",
DisplayName = " ",
Arguments = "67890",
TileOptions = TileOptions.ShowNameOnLogo |
TileOptions.ShowNameOnWideLogo,
Logo = new Uri("ms-appx:///assets/SmallLogo.png"),
WideLogo = new Uri("ms-appx:///assets/WideLogo.png"),
};

bool isPinned = await secondaryTile.RequestCreateAsync();


}

SecondaryTile, ,
.
()
(. 12.9), . -
.
178 12

. 12.9.

TileId , -
(, , . .).
App. -
-
.
,
. OnLaunched -
( App.xaml.cs) args -
TileId , .
, TileId,
12345, ( 12.20).

12.20. ,

protected override void OnLaunched(LaunchActivatedEventArgs args)


{
Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null)
{
...
}

var tileId = args.TileId;


if (tileId == "12345")
{
var secondaryTileArgument = args.Arguments;
"" 179

rootFrame.Navigate(typeof(SecondaryTilePage),
secondaryTileArgument);
}
else if (rootFrame.Content == null)
{
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}

Window.Current.Activate();
}

!
,
, ,
.

12.20 :
, -
, -
.
, , "". -
TileUpdater,
CreateTileUpdaterForSecondaryTile TileUpdateManager TileId -
( 12.21).

12.21.

var updateManager =
TileUpdateManager.CreateTileUpdaterForSecondaryTile("TileId");
updateManager.Update(notification);


. -
Windows Store-, .
, , ,
, .
, -
.
, -
-
.
Taa13

""

Windows Store-
-
Windows 8 , -
.

"-". , , ,
. ,
- , .
-
.
. , ,
"San Francisco" Travel (),
. Maps (),
- , Weather ()
.
Windows Store-,
(Suggestions),
, ,
.
, Windows Store-
. , , -
"" ,
.
.
, , , -

(. 13.1).
"" 181

. 13.1.

, -
, .

. , -
(""), -
, .

"-".
-
. , -
.
.
,
.

Windows Store-. Windows- -
" ( ), ".
Windows XP Windows Vista Microsoft
, UAC (User Account Control -
).
, UAC .
182 13

, -
" , ". , -

, . -
UAC -
, .
, Windows Store-,
" , ".
, ,
.
Windows Store- -
.

""
""
. Blank App -
SearchApp.
"-" , -
, . ,
, .
.
( Package.appxmanifest)
Declarations. Available Declarations Search
Add (. 13.2).
, .
.

OnSearchActivated ( App.xaml.cs).
, .
SearchPage.xaml, Basic Page.
App.xaml.cs OnSearchActivated ( 13.1).

13.1. OnSearchActivated

sealed partial class App : Application


{
public App()
{
...
}

protected override void OnLaunched(LaunchActivatedEventArgs args)


{
Frame rootFrame = Window.Current.Content as Frame;
"" 183

if (rootFrame == null)
{
rootFrame = new Frame();

if (args.PreviousExecutionState ==
ApplicationExecutionState.Terminated)
{
...
}

Window.Current.Content = rootFrame;
}

if (rootFrame.Content == null)
{
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}

Window.Current.Activate();
}

private void OnSuspending(object sender, SuspendingEventArgs e)


{
...
}

protected override void OnSearchActivated(


SearchActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;

if (rootFrame == null)
{
rootFrame = new Frame();
Window.Current.Content = rootFrame;
}

rootFrame.Navigate(typeof(SearchPage), args.QueryText);

Window.Current.Activate();
}
}
184 13

. 13.2.

OnSearchActivated -
( <Enter>).
, SearchPage.xaml -
.
, , OnLaunched
. ,
OnSearchActivated OnLaunched.
, -
. , .
C#- SearchPage.xaml
, OnNavigatedTo. -
, -
( 13.2).

13.2. OnNavigatedTo

public sealed partial class SearchPage : LayoutAwarePage


{
public SearchPage()
"" 185

{
this.InitializeComponent();
}

protected override void OnNavigatedTo(NavigationEventArgs e)


{
var queryText = (string)e.Parameter;
pageTitle.Text = String.Format(" \"{0}\"",
queryText);

base.OnNavigatedTo(e);
}
}

(. 13.3) ( -
).

. 13.3.


, -
.

. ,
, . -
OnSearchActivated,
186 13

. ,
.
,
, . .
OnLaunched ( -
). ,
.
-
. SearchPage.xaml
( 13.3).

13.3. SearchPage.xaml

<Page.BottomAppBar>
<AppBar>
<Button Style="{StaticResource HomeAppBarButtonStyle}"/>
</AppBar>
</Page.BottomAppBar>

HomeAppBarButtonStyle
StandardStyles.xaml. -
( 13.4).

13.4.

private void Button_Click(object sender, RoutedEventArgs e)


{
Frame.Navigate(typeof(MainPage));
}

! .
-
Search Contract,
OnSearchActivated .
, .


, -
. ,
.
, .
-
.
"" 187

Windows Runtime SearchPane


. GetForCurrentView
SearchPane . -

QueryChanged.
,
SearchPage.xaml ( 13.5).

13.5.

protected override void OnNavigatedTo(NavigationEventArgs e)


{
var queryText = (string)e.Parameter;
pageTitle.Text = String.Format(" \"{0}\"",
queryText);

var currentPane = SearchPane.GetForCurrentView();


currentPane.QueryChanged += currentPane_QueryChanged;

base.OnNavigatedTo(e);
}

protected override void OnNavigatedFrom(NavigationEventArgs e)


{
var currentPane = SearchPane.GetForCurrentView();
currentPane.QueryChanged -= currentPane_QueryChanged;

base.OnNavigatedFrom(e);
}

void currentPane_QueryChanged(SearchPane sender,


SearchPaneQueryChangedEventArgs args)
{
pageTitle.Text = String.Format(" \"{0}\"",
args.QueryText);
}


, SearchPage.xaml -
. MainPage.xaml,
SearchPage.xaml
(
).
? ,
(, -
188 13

), -
, -
.


,
, .

SuggestionsRequested SearchPane ( 13.6).

13.6.

protected override void OnNavigatedTo(NavigationEventArgs e)


{
...

var currentPane = SearchPane.GetForCurrentView();


currentPane.QueryChanged += currentPane_QueryChanged;
currentPane.SuggestionsRequested += currentPane_SuggestionsRequested;

base.OnNavigatedTo(e);
}

void currentPane_SuggestionsRequested(SearchPane sender,


SearchPaneSuggestionsRequestedEventArgs args)
{
var defferal = args.Request.GetDeferral();

for (int i = 0; i < 5; i++)


{
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(
String.Format("#{0}. {1}", i, args.QueryText));
}

defferal.Complete();
}

, ,
(. 13.4).

!
SearchPage.xaml.
"" 189

. 13.4.


GetDefferral, deferral.Complete.
,
.
. , .
defferral, , - ,
deferral.Complete. -
.
,
, . -
,
,
.
. -
, . -
,
.
: App.xaml.cs -
Subscribe Unsubscribe ( 13.7) -
.
190 13

13.7.

public void Subscribe()


{
var currentPane = SearchPane.GetForCurrentView();
currentPane.SuggestionsRequested += currentPane_SuggestionsRequested;
}

public void Unsubscribe()


{
var currentPane = SearchPane.GetForCurrentView();
currentPane.SuggestionsRequested -= currentPane_SuggestionsRequested;
}

void currentPane_SuggestionsRequested(SearchPane sender,


SearchPaneSuggestionsRequestedEventArgs args)
{
var defferal = args.Request.GetDeferral();

for (int i = 0; i < 5; i++)


{
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(
String.Format("#{0}. {1}", i, args.QueryText));
}

defferal.Complete();
}

Subscribe OnLaunched
OnSearchActivated, Unsubscribe OnSuspending ( 13.8).

13.8.

protected override void OnLaunched(LaunchActivatedEventArgs args)


{
Subscribe();
// OnLaunched
}

protected override void OnSearchActivated(SearchActivatedEventArgs args)


{
Subscribe();
// OnSearchActivated
}
"" 191

private void OnSuspending(object sender, SuspendingEventArgs e)


{
var deferral = e.SuspendingOperation.GetDeferral();
Unsubscribe();
deferral.Complete();
}

, -
, , , .
. ,
.


,
, , , ,
. , -
SuggestionsRequested ( 13.9).

13.9.

void currentPane_SuggestionsRequested(SearchPane sender,


SearchPaneSuggestionsRequestedEventArgs args)
{
var defferal = args.Request.GetDeferral();

for (int i = 0; i < 2; i++)


{
args.Request.SearchSuggestionCollection.AppendQuerySuggestion(
String.Format("#{0}. {1}", i, args.QueryText));
}

for (int i = 0; i < 2; i++)


{
var image = RandomAccessStreamReference.CreateFromUri(
new Uri("ms-appx:///Assets/SmallLogo.png"));

args.Request.SearchSuggestionCollection.AppendResultSuggestion(
" ", "", "Id", image,
" ");
}

defferal.Complete();
}

. 13.5.
192 13

. 13.5.

, -
.
ResultSuggestionChosen SearchPane ( 13.10).

13.10.

public void Subscribe()


{
var currentPane = SearchPane.GetForCurrentView();
currentPane.SuggestionsRequested += currentPane_SuggestionsRequested;
currentPane.ResultSuggestionChosen += currentPane_ResultSuggestionChosen;
}

void currentPane_ResultSuggestionChosen(SearchPane sender,


SearchPaneResultSuggestionChosenEventArgs args)
{
var id = args.Tag;
}

Tag, -
. -
AppendResultSuggestion.
"" 193

.
. , -
.
-
. .
, , -
, .
Taa14

" "

(Share) Windows Store--


.
"-". ,
, .
-
/. , -
, , , ,
, , , .

. , -
, , "-". -
, , -
(. 14.1).
, -
(. 14.2).
.
,
, .
,
, , . -
, , , .
. -
, .
,
"" . -
.
- SDK (Software Development Kit)
" " 195

. 14.1.

. 14.2.
196 14

( -
), Windows--
. , -
,
( , ,
).
.



Blank App ShareApp.
MainPage.xaml
txtMain, ( 14.1).

14.1. MainPage.xaml

<Page
...
>

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">


<TextBox x:Name="txtMain" AcceptsReturn="True"
Width="450" Height="250"
ScrollViewer.VerticalScrollBarVisibility="Visible"/>
</Grid>
</Page>

DataTransferManager.
"-", -
, , -
DataRequested DataTransferManager.
MainPage,
( 14.2).

14.2. DataRequested

public sealed partial class MainPage : Page


{
public MainPage()
{
this.InitializeComponent();
}
" " 197

protected override void OnNavigatedTo(NavigationEventArgs e)


{
var currentManager = DataTransferManager.GetForCurrentView();
currentManager.DataRequested += currentManager_DataRequested;
}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)


{
var currentManager = DataTransferManager.GetForCurrentView();
currentManager.DataRequested -= currentManager_DataRequested;
}

void currentManager_DataRequested(DataTransferManager sender,


DataRequestedEventArgs args)
{

}
}

,
. ,
. ,
.
, .
, , SetText
DataPackage ( Data args.Request.Data) ( 14.3).

14.3.

void currentManager_DataRequested(DataTransferManager sender,


DataRequestedEventArgs args)
{
if (String.IsNullOrWhiteSpace(txtMain.Text)) return;
var defferal = args.Request.GetDeferral();

args.Request.Data.Properties.Title = " ";


args.Request.Data.Properties.Description = " ";
args.Request.Data.SetText(txtMain.Text);

defferal.Complete();
}

, .
. 14.3 ,
"" .
198 14

. 14.3.

(. 14.1).

14.1.

SetUri URI

SetRtf RTF

SetHtmlFormat HTML HTML-

SetBitmap Bitmap

SetStorageItems StorageItems

SetData

SetDataProvider

. 14.1 - -
, . , -
.

Clipboard. 14.4.
" " 199

14.4.

var data = new DataPackage();


data.SetText(" ");

Clipboard.SetContent(data);

, . 14.1.
, .


, ,
.
Package.appxmanifest Declarations.
Available Declarations Share Target -
Add.
, . -
, Text (. 14.4),

. .
,
OnShareTargetActivated ( App.xaml.cs) (-
14.5). Blank Page TargetPage.xaml,
.

14.5. OnShareTargetActivated

sealed partial class App : Application


{
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}

protected override void OnLaunched(LaunchActivatedEventArgs args)


{
...
}

private void OnSuspending(object sender, SuspendingEventArgs e)


{
...
}
200 14

protected override void OnShareTargetActivated(


ShareTargetActivatedEventArgs args)
{
var frame = new Frame();
frame.Navigate(typeof(TargetPage), args.ShareOperation);

Window.Current.Content = frame;
Window.Current.Activate();
}
}

. 14.4.

OnShareTargetActivated -
TargetPage.xaml,
ShareOperation, .
, TargetPage.xaml
645 , "", -
.
" " 201

TargetPage.xaml ( 14.6).

14.6. TargetPage.xaml

<Page
...
>
<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<TextBox x:Name="txtMain" AcceptsReturn="True"
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
ScrollViewer.VerticalScrollBarVisibility="Visible"
FontSize="24" TextWrapping="Wrap"/>
</Grid>
</Page>

TargetPage.xaml
( 14.7).

14.7.

public sealed partial class TargetPage : Page


{
public TargetPage()
{
this.InitializeComponent();
}

protected override async void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo(e);

if (e.Parameter == null) return;

var shareOperation = (ShareOperation)e.Parameter;


if (shareOpertaion.Data.Contains(StandardDataFormats.Text))
{
txtMain.Text = await shareOpertaion.Data.GetTextAsync();
}
}
}

(
) , ,
.
202 14

- , -
"-". , ,
. . -
TargetPage.xaml (. 14.5).

. 14.5.


.

RandomAccessStreamReference. -
, , . -
( 14.8).

14.8.

void currentManager_DataRequested(DataTransferManager sender,


DataRequestedEventArgs args)
{
var defferal = args.Request.GetDeferral();

args.Request.Data.Properties.Title = "";
args.Request.Data.Properties.Description = "";
" " 203

var uri = new Uri("http://foo.com/microsoftlogo.png");


var streamReference = RandomAccessStreamReference.CreateFromUri(uri);
args.Request.Data.SetBitmap(streamReference);

defferal.Complete();
}

, , -
( 14.9).

14.9. ,

var uri = new Uri("ms-appx:///Assets/Logo.png");


Bitmap. , Image imgMain.
( 14.10).

14.10.

protected override async void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo(e);

if (e.Parameter == null) return;

var shareOperation = (ShareOperation)e.Parameter;


if (shareOpertaion.Data.Contains(StandardDataFormats.Bitmap))
{
var bitmapReference = await shareOpertaion.Data.GetBitmapAsync();
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(await bitmapReference.OpenReadAsync());
img.Source = bitmapImage;
}
}



(Text, Bitmap, URI . .) -
. -
, - . , -
( , , ,
. .), Text, -
204 14

, . , ,
, ,
, .
SetData, ,
"Product". SetData
, XML, JSON (JavaScript Object
Notation). JSON, . . -
, JavaScript, C#, Visual Basic C++.
, -
( "Product"),
, JSON.
-
, ,
, -
, .
, -
- . , .
,
, http://schema.org.
, -
http://schema.org/Product, -,
Product, ,
-
!
( 14.11).

14.11.

void currentManager_DataRequested(DataTransferManager sender,


DataRequestedEventArgs args)
{
var defferal = args.Request.GetDeferral();
var dataPackage = args.Request.Data;
dataPackage.Properties.Title = " ";

var productFormat =
@"{
""type"" : ""http://schema.org/Product"",
""properties"" :
{
""name"" : ""{0}"",
""description"" : ""{1}"",
""productID"" : ""{2}""
}
}";
" " 205

var productJson = String.Format(productFormat,


"Nokia Lumia 920", " ", "8410660101481");

dataPackage.SetData("http://schema.org/Product", productJson);
defferal.Complete();
}

-. , -
, http://
schema.org/Product.
JSON ( 14.12).

14.12. JSON

protected async override void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo(e);

if (e.Parameter == null) return;

var dataPackageView = ((ShareOperation)e.Parameter).Data;


var productJson = await
dataPackageView.GetTextAsync("http://schema.org/Product");
JsonObject productObject = JsonObject.Parse(productJson);
JsonObject properties = productObject["properties"].GetObject();

var productId = properties["productID"];


var productName = properties["name"];
var productDescriptions = properties["description"];
}

JSON JsonObject -
Windows.Data.Json.
, , -
.
, http://schema.org
JSON.

,
"" (, ) .
.
SetData. , - "" -
.

, - , -
"" . -
206 14

. ,
.


, ,
, . -
"" .
, ,
( 14.13).

14.13.

void currentManager_DataRequested(DataTransferManager sender,


DataRequestedEventArgs args)
{
args.Request.Data.Properties.Title = "";
args.Request.Data.SetDataProvider("product", DataHandler);
}

private async void DataHandler(DataProviderRequest request)


{
var defferal = request.GetDeferral();

try
{

}
finally
{
defferal.Complete();
}
}

BinaryDataHandler .
( 1 10 000) (-
14.14).

14.14.

private async void BinaryDataHandler(DataProviderRequest request)


{
var defferal = request.GetDeferral();

try
{
var stream = new InMemoryRandomAccessStream();
" " 207

using (var writer = new DataWriter(stream))


{
for (int i = 0; i < 10000; i++)
{
writer.WriteInt32(i);
}

await writer.StoreAsync();
await writer.FlushAsync();
writer.DetachStream();
}

stream.Seek(0);
request.SetData(stream);
}
finally
{
defferal.Complete();
}
}

,
InMemoryRandomAccessStream.
.
, -
(,
, "-
" . .), -
.
-
ReportStarted ShareOperation. -
ReportDataRetreived. -
- . -
, ReportCompleted ( 14.15).
-.

14.15.

protected async override void OnNavigatedTo(NavigationEventArgs e)


{
base.OnNavigatedTo(e);

if (e.Parameter == null) return;

var shareOperation = (ShareOperation)e.Parameter;


shareOperation.ReportStarted();
208 14

//
shareOperation.ReportDataRetrieved();
//
shareOperation.ReportCompleted();
}

- , -
c ReportError ( 14.16).

14.16.

shareOperation.ReportError(" ");

,
, -,
( -).
.
, -
, .

, /. -
-
.
,
.
. -
.
Taa15

""

"-" (Settings).
.
Windows-
. Windows Store-
.
"-".
"-" ,
. , -
( ),
. Bing Weather -
. 15.1.
-
, .


.
Blank App SettingsApp.
, App.xaml.cs.
SettingsPane. -
CommandsRequested -
.
Subscribe Unsubscribe
, ( 15.1). -
-
.
210 15

. 15.1.

15.1. CommandsRequested

sealed partial class App : Application


{
...

protected override void OnLaunched(LaunchActivatedEventArgs args)


{
...
Subscribe();

Window.Current.Activate();
}

private void OnSuspending(object sender, SuspendingEventArgs e)


{
var deferral = e.SuspendingOperation.GetDeferral();
Unsubscribe();
deferral.Complete();
}

public void Subscribe()


{
var currentPane = SettingsPane.GetForCurrentView();
"" 211

currentPane.CommandsRequested += currentPane_CommandsRequested;
}

public void Unsubscribe()


{
var currentPane = SettingsPane.GetForCurrentView();
currentPane.CommandsRequested -= currentPane_CommandsRequested;
}

void currentPane_CommandsRequested(SettingsPane sender,


SettingsPaneCommandsRequestedEventArgs args)
{

}
}

, -
Permissions (. 15.2).
.
SettingsCommand, args.Request.
ApplicationCommands ( 15.2).

15.2.

void currentPane_CommandsRequested(SettingsPane sender,


SettingsPaneCommandsRequestedEventArgs args)
{
var applicationCommands = args.Request.ApplicationCommands;

var newComand = new SettingsCommand("Id_", "", cmd =>


{
//
});
applicationCommands.Add(newComand);

var aboutCommand = new SettingsCommand("About", " ", cmd =>


{
Frame.Navigate(typeof(AboutPage));
});
applicationCommands.Add(aboutCommand);

var siteCommand = new SettingsCommand("Site", " ", cmd =>


{
Launcher.LaunchUriAsync(new Uri("http://techdays.ru"));
});
applicationCommands.Add(siteCommand);
}
212 15

,

, .
. 15.3.

. 15.2. . 15.3.

, .
:
, , ,
.
"" 213

,
.
, .


-
.
Basic Page, .
SettingsFlyout.xaml.

XAML- . -
MSDN:

http://code.msdn.microsoft.com/windowsapps/App-settings-sample-1f762f49.

,
.
Popup, ( 15.3).
-
.

15.3.

private Popup _settingsPopup;


void currentPane_CommandsRequested(SettingsPane sender,
SettingsPaneCommandsRequestedEventArgs args)
{
var applicationCommands = args.Request.ApplicationCommands;

var newComand = new SettingsCommand("Id_", "", cmd =>


{
_settingsPopup = new Popup();
_settingsPopup.IsLightDismissEnabled = true;
_settingsPopup.Width = 646;
_settingsPopup.Height = Window.Current.Bounds.Height;
_settingsPopup.ChildTransitions = new TransitionCollection();
_settingsPopup.ChildTransitions.Add(new PaneThemeTransition()
{
Edge = (SettingsPane.Edge == SettingsEdgeLocation.Right) ?
EdgeTransitionLocation.Right :
EdgeTransitionLocation.Left
});

SettingsFlyout mypane = new SettingsFlyout();


mypane.Width = 646;
mypane.Height = Window.Current.Bounds.Height;
214 15

_settingsPopup.Child = mypane;
_settingsPopup.SetValue(Canvas.LeftProperty,
SettingsPane.Edge == SettingsEdgeLocation.Right
? (Window.Current.Bounds.Width 646) : 0);

_settingsPopup.SetValue(Canvas.TopProperty, 0);
_settingsPopup.IsOpen = true;
});

applicationCommands.Add(newComand);

...
}


(. 15.4).

. 15.4.
"" 215

!
,
"" "".
.

,
"-". -
().
, , -
, .

. Popup
.
Taa16

Windows Store- ,
Windows-.
Windows Store-
, . . "" (Sandbox).
, , C:\ .
Windows Store-
, ( -
). -
,
(
17). -
, SQLite,
.


Windows Store- -
( , -
), . -
:
 LocalFolder;
 RoamingFolder;
 TemporaryFolder.
.
:
 LocalSettings;
 RoamingSettings.
217

, -
. -
.
, LocalFolder, , -
. ,
, , SQLite , -
.
RoamingFolder -
, . -
, -
RoamingFolder . -
(RoamingSettings).
. ,
,
RoamingFolder , -
, .
(, -
). RoamingFolder
, , . .
100 .
, RoamingFolder -
!


, RoamingFolder, .

.
RoamingStorageQuota ( 16.1).

16.1.

ApplicationData.Current.RoamingStorageQuota

, RoamingFolder RoamingSettings
.
. , -
RoamingFolder , -
.
TemporaryFolder . ,
-
.
.
218 16


(string, bool, int,
float . .) ,
LocalSettings RoamingSettings. ,
RoamingSettings .
( ,
. .).
LocalSettings. -
( 16.2).

16.2. LocalSettings

ApplicationData.Current.LocalSettings.Values["MyKey"] = "";

, ( 16.3).

16.3. LocalSettings

var val = (string)ApplicationData.Current.LocalSettings.Values["MyKey"];

,
NullReferenceException (bool, int, float
. .) ( 16.4).

16.4.

var settings = ApplicationData.Current.LocalSettings;


if (settings.Values.ContainsKey("PageNumber"))
{
var number = (int)settings.Values["PageNumber"];
}

, RoamingSettings, -
. , -
1015 . -
, RoamingSettings
HighPriority, -
. 1530
( 16.5).

16.5.

ApplicationData.Current.RoamingSettings.Values["HighPriority"] = 42;
219


.
, (LocalFolder, RoamingFolder
TempraryFolder), .
, . -
( 16.6).

16.6.

var folder = ApplicationData.Current.LocalFolder;


//var folder = ApplicationData.Current.RoamingFolder;
//var folder = ApplicationData.Current.TemporaryFolder;

16.6 -
.
FileIO. test.txt
"Hello World!" ( 16.7).

16.7.

var folder = ApplicationData.Current.LocalFolder;


var file = await folder.CreateFileAsync("test.txt",
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, "Hello World!");

16.8.

16.8.

var storageFolder = ApplicationData.Current.LocalFolder;


var file = await storageFolder.GetFileAsync("test.txt");
var text = await FileIO.ReadTextAsync(file);


RoamingFolder.
, , , ,
, .
DataChanged ( 16.9).

16.9.

ApplicationData.Current.DataChanged += (sender, args) =>


{
//
};
220 16

, -
, . , -
, . , -
, -
.
( ) .
Windows 8 -
. , .
, -
. -
ApplicationData.Current.Version.
.



, 1.

SetVersionAsync (-
16.10).

16.10.

await ApplicationData.Current.SetVersionAsync(versionNumber,
UpgradeToVersionHandler);

versionNumber , UpgradeToVersion-
Handler ( 16.11).

16.11.

private void UpgradeToVersionHandler(SetVersionRequest setversionrequest)


{
var defferal = setversionrequest.GetDeferral();
if (setversionrequest.DesiredVersion >
setversionrequest.CurrentVersion)
{
// ;
}
defferal.Complete();
}


. , -
.
( ).
221



.
, , XAML-. Windows 8
:
 ms-appx:/// , ;
 ms-appdata:///local/ LocalFolder;
 ms-appdata:///roaming/ RoamingFolder;
 ms-appdata:///temp/ TemporaryFolder.
16.12 .

16.12.

LocalImage.Source = new BitmapImage(


new Uri("ms-appdata:///local/appDataLocal.png"));
RoamingImage.Source = new BitmapImage(
new Uri("ms-appdata:///roaming/appDataRoaming.png"));
TempImage.Source = new BitmapImage(
new Uri("ms-appdata:///temp/appDataTemp.png"));

Path
. ,
ApplicationData.Current.LocalFolder.Path:
C:\Users\<UserName>\AppData\Local\Packages\f7cb881e-53dd-47d9-b559-
57defb00a8fb_1ajdc8xvgt2ym\LocalState\

<UserName> , , f7cb881e-
53dd-47d9-b559-57defb00a8fb_1ajdc8xvgt2ym .
Windows Explorer,
.

SQLite
, -
, .
(). Windows 8
(). -
,
. SQLite, , -
.
SQL.
222 16

. , SQLite
Windows Store-.
SQLite -
. Tools | Extensions and Updates -
SQLite for Windows Runtime (. 16.1).

. 16.1. SQLite for Windows Runtime

Visual Studio. -
SQLite Windows Store-.
Blank App SqliteApp.
References ( Solution
Explorer) Add Reference... -
SQLite for Windows Runtime Microsoft Visual C++ Runtime Package
(. 16.2).

!
Microsoft Visual C++ Runtime Package.
, , -
Windows Store.

SQLite for Windows Runtime , ()


. SQLite for Windows Runtime , -
C++, (Any CPU),
C#. -
, .
Visual Studio BUILD | Configuration
Manager... Active solution
223

platform x86 ( Visual Studio 32- -


x86, Windows Store-
) (. 16.3).
Windows Store -
(x86, x64, ARM), -
, SQLite for Windows Runtime.

. 16.2. SQLite

. 16.3.
224 16

.NET- -
ORM (Object-Relational Mapping), -
LINQ (Language Integrated Quiries). SQLite -
. sqlite-net.
Solution Explorer Manage
NuGet Packages..., sqlite-net (. 16.4).

. 16.4. sqlite-net

, .
16.13.
, .

16.13.

var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path, "data.db");


using (var db = new SQLiteConnection(dbPath))
{
//
}

SQLite . -
- , Microsoft SQL Server Oracle Database.
Windows Store-.
sqlite-net LINQ-,
ADO.NET. .
225

, . ,
, . -
,
250 (-
16.14).

16.14.

public class Product


{
[PrimaryKey, AutoIncrement]
public int ProductId { get; set; }
[MaxLength(250)]
public string Name { get; set; }
}

.
Product ( 16.15).

16.15.

private void InitDb()


{
var dbPath = Path.Combine(ApplicationData.Current.LocalFolder.Path,
"data.db");

using (var db = new SQLiteConnection(dbPath))


{
db.CreateTable<Product>();
}
}

-
data.db. SQLite, -
, SQLite. -
, SQLite, SQLite Expert
Personal:
http://www.sqliteexpert.com/download.html.
SQLite Expert Personal
Product (. 16.5).
.
Product ( 16.16).
226 16

. 16.5. SQLite Expert Personal

16.16.

using (var db = new SQLiteConnection(dbPath))


{
var product = new Product() { Name = "Visual Studio 2012" };

db.Insert(product);
}

, 16.16, ProductId
Product .
( 16.17).

16.17.

using (var db = new SQLiteConnection(dbPath))


{
var products = from c in db.Table<Product>()
where c.Name == "Visual Studio 2012"
select c;
}

, SQL-. , -
2 ( 16.18).
227

16.18. SQL-

using (var db = new SQLiteConnection(dbPath))


{
var products = db.Query<Product>(
"SELECT * FROM Product WHERE ProductId=?", 2);
var product = products.FirstOrDefault();
}

( 16.19).

16.19.

using (var db = new SQLiteConnection(dbPath))


{
db.Delete<Product>(3);
}

LINQ, (, -
) -
SQL-.
SQL-, ( 16.20).

16.20. SQL-

using (var db = new SQLiteConnection(dbPath))


{
var command = db.CreateCommand(
"INSERT INTO Product (Name) VALUES (?)", "Windows 8");
command.ExecuteNonQuery();
}


. 16.21 , -
Product.

16.21. ,

using (var db = new SQLiteConnection(dbPath))


{
var command = db.CreateCommand(
"SELECT COUNT(ProductId) FROM Product");
var count = command.ExecuteScalar<int>();
}
228 16

Windows 8 Windows .
Windows 8
. -
, ,
.
Windows Store- -
: LocalFolder, RoamingFolder TemporaryFolder,
, .
.
, , -
. -
SQLite.
Taa17



, , Windows Store-
.
. -
, -
, 16.
, .
, .
- ,
"", ,
.
.

FileOpenPicker
FileOpenPicker , , -
, OpenFileDialog Windows Forms. FileOpenPicker
. ,
.
FileOpenPicker 17.1.

17.1. FileOpenPicker

var openPicker = new FileOpenPicker();


openPicker.FileTypeFilter.Add("*");
var file = await openPicker.PickSingleFileAsync();

FileOpenPicker -
, . (-
230 17

, ,
), "*".
, ,
".jpg".
( 17.2).

17.2. FileOpenPicker

FileOpenPicker openPicker = new FileOpenPicker();


openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
var file = await openPicker.PickSingleFileAsync();

if(file!=null)
{
...
}

, . -
NULL.
PickMultipleFilesAsync (-
17.3).

17.3.

var openPicker = new FileOpenPicker();


openPicker.FileTypeFilter.Add("*");
var files = await openPicker.PickMultipleFilesAsync();

FileOpenPicker ,
. , , , ,
FileOpenPicker "" (-
17.4).

17.4.

openPicker.SuggestedStartLocation = PickerLocationId.VideosLibrary;

, , "",
"" . .:
 DocumentsLibrary;
 ComputerFolder;
231

 Desktop;
 Downloads;
 HomeGroup;
 MusicLibrary;
 PicturesLibrary;
 VideosLibrary.
, , :
( ) ( 17.5).

17.5.

openPicker.ViewMode = PickerViewMode.Thumbnail;

. ,
, ""
( 17.6).

17.6.

openPicker.CommitButtonText = "";

, FileOpenPicker ,
17.7.

17.7. FileOpenPicker

var openPicker = new FileOpenPicker();


openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.CommitButtonText = "";
var file = await openPicker.PickSingleFileAsync();

if (file != null)
{
//
}

. 17.1.
232 17

. 17.1.

!
, ,
, SkyDrive. ,
, -
.

FileSavePicker
FileSavePicker, -
SaveFileDialog Windows Forms. FileSavePicker -
.
17.8.

17.8.

var savePicker = new FileSavePicker();


savePicker.FileTypeChoices.Add("", new List<string>() { ".txt" });
savePicker.SuggestedFileName = "hello";
var file = await savePicker.PickSaveFileAsync();
if (file != null)
{
CachedFileManager.DeferUpdates(file);
await FileIO.WriteTextAsync(file, "Hello World!");
CachedFileManager.CompleteUpdatesAsync(file);
}
233

, ,
NULL, -
NullReferenceException.
.
, ( SkyDrive).
,
CachedFileManager.

FolderPicker
, -
, . -
.
-
FolderPicker, FolderBrowserDialog
Windows Forms ( 17.9).

17.9. FolderPicker

var folderPicker = new FolderPicker();


folderPicker.FileTypeFilter.Add("*");
//
var folder = await folderPicker.PickSingleFolderAsync();
//
var files = await folder.GetFilesAsync();
//
var newFile = await folder.CreateFileAsync("hello.txt");
await FileIO.WriteTextAsync(newFile, "Hello World!");



, -
,
(. 17.2). ,
,
"" .

, .
, :
 Documents Library;
 Music Library;
234 17

 Pictures Library;
 Videos Library;
 Removable Storage.

. 17.2.

Documents Library ,
.
Documents Library.
File
Type Associations.

KnownFolders ( 17.10).

17.10. Picture Folder


( )

var folder = KnownFolders.PicturesLibrary;

, :
 KnownFolders.HomeGroup;
 KnownFolders.MediaServerDevices.
235



( ).

File Open Picker


FileOpenPicker FileSavePicker
, . , -
SkyDrive Facebook,
.
, - -
-
. , -
, -
File Open Picker (. 17.3).

. 17.3. File Open Picker


. ,
Supports any file type.
236 17

, -
. ,
FileOpenPage.xaml ( 17.11).

17.11. XAML- FileOpenPage.xaml

<Page
...
>

<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<StackPanel VerticalAlignment="Center"
HorizontalAlignment="Center">
<TextBlock Text=" FileOpenPage.xaml" FontSize="72" />
<Button Content=" " HorizontalAlignment="Center"/>
</StackPanel>
</Grid>
</Page>

App.xaml.cs
OnFileOpenPickerActivated,
( 17.12).

17.12. OnFileOpenPickerActivated App.xaml.cs

sealed partial class App : Application


{
...

protected override void OnFileOpenPickerActivated(


FileOpenPickerActivatedEventArgs args)
{
base.OnFileOpenPickerActivated(args);

var frame = new Frame();


Window.Current.Content = frame;
frame.Navigate(typeof(FileOpenPage), args);
Window.Current.Activate();
}
}

File Open Picker -


FileOpenPage.xaml,
237

. -
, () args.
FileOpenPage.xaml
( 17.13). Logo.png -
.

17.13.

public sealed partial class FileOpenPage : Page


{
public FileOpenPage()
{
this.InitializeComponent();
}

private FileOpenPickerActivatedEventArgs _args;


protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
_args = e.Parameter as FileOpenPickerActivatedEventArgs;
}

private async void Button_Click(object sender, RoutedEventArgs e)


{
var file = await Package.Current.InstalledLocation.GetFileAsync(
@"Assets\Logo.png");

if (_args != null)
{
var result = _args.FileOpenPickerUI.AddFile("fileId", file);
}
}
}

17.13 ,
, . ,
IStorageFile, -
, ,
.
, FileOpenPicker,
(. 17.4).

(. 17.5).
238 17

. 17.4.

. 17.5. FileOpenPage.xaml
239

File Save Picker


, -
. , SkyDrive ,
"" .
File Open Picker
File Save Picker ,
OnFileSavePickerActivated .


File Save
Picker.

StorageApplicationPermissions

. -
, ,
. ,
, , -
.
Windows 8
.
, , , FileOpenPicker,
-
( 17.14).

17.14.

var filePicker = new FileOpenPicker();


filePicker.FileTypeFilter.Add("*");
var file = await filePicker.PickSingleFileAsync();

var fileToken = StorageApplicationPermissions.FutureAccessList.Add(file);

FutureAccessList.Add,
, -
.
( 17.15).

17.15.

var accessList = StorageApplicationPermissions.FutureAccessList;


if (accessList.ContainsItem(fileToken))
240 17

{
var file = await accessList.GetFileAsync(fileToken);
}


FutureAccessList.Entries.
,
, -
( 17.16).

17.16.

var fileToken = StorageApplicationPermissions.FutureAccessList.Add(file,


file.DisplayName);



. , -
, ,

.

File Type Associations.
,
txt, png . . qwerty
(. 17.6).
,
.
( Icon.png).
App.xaml.cs
OnFileActivated ( 17.17).

17.17.

sealed partial class App : Application


{
...

protected override void OnFileActivated(FileActivatedEventArgs args)


{
var frame = new Frame();
Window.Current.Content = frame;
241

frame.Navigate(typeof(MainPage), args.Files);
Window.Current.Activate();
}
}

. 17.6.

() MainPage.xaml. -
MainPage.xaml , .
( 17.18).

17.18.

public sealed partial class MainPage : Page


{
public MainPage()
242 17

{
this.InitializeComponent();
}

protected override void OnNavigatedTo(NavigationEventArgs e)


{
var files = e.Parameter as IReadOnlyList<IStorageItem>;
if (files != null)
{
StringBuilder sb = new StringBuilder();
foreach (var file in files)
{
sb.AppendLine(file.Name);
}

MessageDialog msg = new MessageDialog(sb.ToString());


msg.ShowAsync();
}
}

...
}

, qwerty
(. 17.7). .
qwerty .
.
, . -
, FTP- ftp,
http https. -
qwerty.
Protocol (. 17.8).

OnActivated App.xaml.cs ( 17.19).

17.19.

sealed partial class App : Application


{
...

protected override void OnActivated(IActivatedEventArgs args)


{
if (args.Kind == ActivationKind.Protocol)
{
var protocolArgs = args as ProtocolActivatedEventArgs;
var uri = protocolArgs.Uri;
243

. 17.7.

. 17.8.
244 17

var rootFrame = new Frame();


rootFrame.Navigate(typeof(MainPage), uri);
Window.Current.Content = rootFrame;
}

Window.Current.Activate();
}
}

MainPage.xaml
, .

FileOpenPicker
FileSavePicker, FolderPicker.

StorageApplicationPermissions,
.
,
"", .

.
File Open Picker File Save Picker
, -
.
, , txt -
, , ftp.
Taa18

(Web-
) . -
, -
. ,
,
, .
, .
Windows 8 .
,
, .
, . -
.
,
. Blank App
Camera App.
,
Webcam. ,
Microphone (. 18.1).

CameraCaptureUI
-
/ CameraCaptureUI. , -
( ), . -
CameraCaptureUI , -
. , ,
.
246 18

. 18.1.

MainPage.xaml ,
Image. XAML-
MainPage 18.1.

18.1. MainPage

<Page
...
>

<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<Button Content=" "/>
<Image x:Name="imgMain" Width="640" Height="480"/>
</Grid>
</Page>

. -
CameraCaptureUI ( 18.2).
247

18.2.

private async void Button_Click(object sender, RoutedEventArgs e)


{
var camera = new CameraCaptureUI();
StorageFile file = await
camera.CaptureFileAsync(CameraCaptureUIMode.Photo);

if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await
file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream);
}

imgMain.Source = bitmapImage;
}
}

18.2
, , -
, Image .

!
NULL. -
( "").
NULL. -
NULL, -
.

. -
,
, (. 18.2).
, , -
, -
, ,
.
CameraCaptureUIMode.Photo CameraCaptureUIMode.Video,
, .
. -
MediaElement ( 18.3).
248 18

. 18.2.

18.3. MediaElement

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">


<Button Content=" " Click="Button_Click" />
<MediaElement x:Name="meMain" Width="640" Height="480"/>
</Grid>

( 18.4).

18.4.

private async void Button_Click(object sender, RoutedEventArgs e)


{
var camera = new CameraCaptureUI();
StorageFile file = await
camera.CaptureFileAsync(CameraCaptureUIMode.Video);

if (file != null)
{
IRandomAccessStream fileStream = await
file.OpenAsync(FileAccessMode.Read);
meMain.SetSource(fileStream, "video/mp4");
}
}
249

CameraCaptureUIMode.Video,
CameraCaptureUIMode.PhotoOrVideo. -
.



CameraCaptureUI PhotoSettings VideoSettings, -
. -
.

PhotoSettings.AllowCropping
AllowCropping ( true) ,
( 18.5). , -
.

18.5. AllowCropping

var camera = new CameraCaptureUI();


camera.PhotoSettings.AllowCropping = true;

PhotoSettings.CroppedAspectRatio
CroppedAspectRatio -
. , , , -
.
18.6 , 2 1
.

18.6.

var camera = new CameraCaptureUI();


camera.PhotoSettings.CroppedAspectRatio = new Size(2,1);

, -
. ,
AllowCropping false. , -
CroppedAspectRatio CroppedSizeInPixels.

PhotoSettings.CroppedSizeInPixels
, ,
, CroppedSizeInPixels,
250 18

, (-
18.7).

18.7.

var camera = new CameraCaptureUI();


camera.PhotoSettings.CroppedSizeInPixels = new Size(200,200);

, . -,
. ,
, ,
, . -
, , -
, , -
.

PhotoSettings.Format
Format CameraCaptureUIPhotoFormat -
. : JPEG, PNG JPEG XR.
JPEG XR , Windows
Media Photo. , JPEG. JPEG
XR .
JPEG XR 18.8.

18.8.

var camera = new CameraCaptureUI();


camera.PhotoSettings.Format = CameraCaptureUIPhotoFormat.JpegXR;


JPEG XR , . .
. , -
JPEG ( ) PNG.

PhotoSettings.MaxResolution
, ,
. MaxResolution
CameraCaptureUIMaxPhotoResolution :
 HighestAvailable ( -
);
 VerySmallQvga ( 320240);
 SmallVga ( 320240);
251

 MediumXga ( 1024768);
 Large3M ( 19201080);
 VeryLarge5M ( 5 ).
( 18.9).

18.9.

var camera = new CameraCaptureUI();


camera.PhotoSettings.MaxResolution=
CameraCaptureUIMaxPhotoResolution.MediumXga;


VideoSettings.AllowTrimming
, "" -
. AllowTrimming
( 18.10).

18.10. AllowTrimming

var camera = new CameraCaptureUI();


camera.VideoSettings.AllowTrimming = false;

VideoSettings.Format
Format , ,
( 18.11).
MP4 ( ) WMV.

18.11.

var camera = new CameraCaptureUI();


camera.VideoSettings.Format = CameraCaptureUIVideoFormat.Wmv;

VideoSettings.MaxDurationInSeconds
MaxDurationInSeconds -
( 18.12).
. -
AllowTrimming false. , -
- ,
,
, .
252 18

18.12.

var camera = new CameraCaptureUI();


camera.VideoSettings.MaxDurationInSeconds = 10;

VideoSettings.MaxResolution
, -
( 18.13). MaxResolution
:
 HighestAvailable ;
 LowDefinition ;
 StandardDefinition ;
 HighDefinition .
, -
. ,
MaxResolution.

18.13.

var camera = new CameraCaptureUI();


camera.VideoSettings.MaxResolution =
CameraCaptureUIMaxVideoResolution.HighDefinition;

MediaCapture
/
/ . ,
,
,
. MediaCapture, c -
,
.
.
MediaCapture ( 18.14). -
-
.

18.14. MediaCapture

private MediaCapture _mediaCapture;


protected override async void OnNavigatedTo(NavigationEventArgs e)
253

{
if (_mediaCapture == null)
{
_mediaCapture = new MediaCapture();

try
{
await _mediaCapture.InitializeAsync();
_mediaCapture.RecordLimitationExceeded += async (sender) =>
{
//
await _mediaCapture.StopRecordAsync();
};

}
catch (UnauthorizedAccessException)
{
//
}
}
}

, -
StartRecordToStorageFileAsync,
, IStorageFile.
(
CameraCaptureUI,
). StartRecordToStreamAsync
.
, -
.
MainPage.xaml.
, , . -
( 18.15).

18.15.

private InMemoryRandomAccessStream _stream;


//
private async void Start_Button_Click(object sender, RoutedEventArgs e)
{
try
{
_stream = new InMemoryRandomAccessStream();
var encodingProfile =
MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Auto);
254 18

await _mediaCapture.StartRecordToStreamAsync(encodingProfile,
_stream);
}
catch (Exception ex)
{
//
}
}

//
private async void Stop_Button_Click(object sender, RoutedEventArgs e)
{
await _mediaCapture.StopRecordAsync();
}

//
private void Play_Button_Click(object sender, RoutedEventArgs e)
{
meMain.SetSource(_stream, "audio/mp3");
meMain.Play();
}

, , .
, MP3 -
MediaEncodingProfile.CreateMp3.
MediaElement,
CameraCaptureUI .
.
CaptureElement,
( 18.16).

18.16. CaptureElement

<CaptureElement x:Name="ceMain" Width="1024" Height="768" />

MediaCapture
CaptureElement StartPreviewAsync
( 18.17).

18.17.

ceMain.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();

"" , -
MainPage.xaml (. 18.3).
255

. 18.3. ""

,
"" ( 18.18). -
. ,
() "", 17.

18.18.

private StorageFile _recordVideoFile;


//
private async void Start_Button_Click(object sender, RoutedEventArgs e)
{
try
{
_recordVideoFile =
await KnownFolders.VideosLibrary.CreateFileAsync("video.mp4",
CreationCollisionOption.GenerateUniqueName);

var encodingProfile =
MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
await _mediaCapture.StartRecordToStorageFileAsync(
encodingProfile, _recordVideoFile);
}
256 18

catch (Exception ex)


{
//
}
}

MediaCapture
CapturePhotoToStorageFileAsync CapturePhotoToStreamAsync. ,
, ,
- .


MediaCapture
,
. CameraCaptureUI -
. , -
?
DeviceInformation.
, -
( 18.19).

18.19.

var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);


var microphones = await
DeviceInformation.FindAllAsync(DeviceClass.AudioCapture);

var camera = cameras.FirstOrDefault();


var microphone = microphones.FirstOrDefault();

if (camera != null && microphone != null)


{
var settings = new MediaCaptureInitializationSettings()
{
AudioDeviceId = microphone.Id,
VideoDeviceId = camera.Id
};

await _mediaCapture.InitializeAsync(settings);
}

MediaCapture
VideoDeviceController.
257

:
 BacklightCompensation ;
 Brightness ;
 Contrast ;
 Exposure ;
 Focus ;
 Hue ;
 Pan ;
 Roll ;
 Tilt ;
 WhiteBalance ;
 Zoom .

,
CameraOptionsUI ( 18.20).

18.20.

CameraOptionsUI.Show(_mediaCapture);

(. 18.4)
, , -
.
AudioDeviceController
:
 Muted ( -
true false);
 VolumePercent (-
0 100).

. 18.4. CameraOptionsUI
258 18

Windows Store-.
/ .
CameraCaptureUI.
, ( , ),
.
.
"" ,
. ,
CameraCaptureUI, .
-
, , , -
.
.
Taa19



,
. , Bing Maps Microsoft, -
, , ,
. .
,
,
. , ,
, , -
, ,
. , ,
, . , -
-
, . ,
, , -
. - -
, , -
, .
-
, Bing Maps SDK,
Microsoft.
Windows 8, Bing Maps SDK . -
, -
SDK Windows 8, Bing.


,
, -
. GPS (Global Position System), -
260 19

, -
Wi-Fi, IP-. -
. , , -
, IP-
50 , , Wi-Fi,
350 , / GPS 10 .
, -
-
, .

. ,
.
.
,
, , GPS (
IP-) .
. -
( ) (
Active Directory) ,
.
, -
, -
. ,

. , -
,
. ,
Airplane Mode, -
.


-
. Blank App
LocationApp.
Package.appxmanifest Capabilities
Location (. 19.1).
MainPage.xaml -
( 19.1).
,
txtLatitide, txtLongitude txtAccuracy .
261

. 19.1.

19.1. XAML- MainPage

<Page
...
>
<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>

<Button x:Name="btnLocation"
Content=" " Grid.Row="0"
VerticalAlignment="Center" HorizontalAlignment="Center"
Margin="10" />

<StackPanel Grid.Row="1"
Orientation="Vertical" VerticalAlignment="Top"
HorizontalAlignment="Center">
<TextBlock x:Name="txtAccuracy" Style="{StaticResource
HeaderTextStyle}" Margin="5"/>
262 19

<TextBlock x:Name="txtLatitide" Style="{StaticResource


HeaderTextStyle}" Margin="5"/>
<TextBlock x:Name="txtLongitude" Style="{StaticResource
HeaderTextStyle}" Margin="5"/>
</StackPanel>

</Grid>
</Page>

API , -
, -
( ).

btnLocation.
.

Geolocator Windows.Devices.Geolocation. -

GetGeopositionAsync ( 19.2).

19.2.

private async void BtnLocationClick(object sender, RoutedEventArgs e)


{
var geolocator = new Geolocator();

try
{
var position = await geolocator.GetGeopositionAsync();

txtAccuracy.Text = String.Format(" {0} ",


position.Coordinate.Accuracy);
txtLatitide.Text = String.Format(": {0}",
position.Coordinate.Latitude);
txtLongitude.Text = String.Format(": {0}",
position.Coordinate.Longitude);
}
catch (Exception)
{
// -
}
}

GetGeopositionAsync Geoposition,
Coordinate Geooordinate. Geooordinate -
(. 19.1).
263

19.1. Geooordinate

Accuracy
Latitude
Longitude
Speed
Altitude
AltitudeAccuracy
Heading

Timestamp ,

, (,
IP-), null.
. btnLocation
, -
(. 19.2). ,
(. 19.3).

. 19.2.

. 19.3.

, -
, DesiredAccuracy
Geolocator ( 19.3).
.
264 19

19.3.

var geolocator = new Geolocator();


geolocator.DesiredAccuracy = PositionAccuracy.High;

-
, , ,
. -
.

( ). -
. -
LocationStatus
Geolocator. -
StatusChanged.
, -
, Disabled.
.
Geolocator
. ,
Geolocator .
,
-
. btnLocation.


, -
.
- , , , . .
.
, Geolocator

PositionChanged ( 19.4).

19.4.

public sealed partial class MainPage : Page


{
private Geolocator _geolocator;

public MainPage()
{
InitializeComponent();
}
265

private void BtnLocationClick(object sender, RoutedEventArgs e)


{
if (_geolocator != null) _geolocator.PositionChanged -=
GeolocatorPositionChanged;

_geolocator = new Geolocator();


_geolocator.PositionChanged += GeolocatorPositionChanged;
}

void GeolocatorPositionChanged(Geolocator sender,


PositionChangedEventArgs args)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var position = args.Position;
txtAccuracy.Text = String.Format(" {0} ",
position.Coordinate.Accuracy);
txtLatitide.Text = String.Format(": {0}",
position.Coordinate.Latitude);
txtLongitude.Text = String.Format(": {0}",
position.Coordinate.Longitude);
});
}
}

,
, -
( ) -
Dispatcher.RunAsync.
PositionChanged? -
, -
. -
MovementThreshold ( ) Geolocator. -
19.5 , .

19.5.

_geolocator = new Geolocator();


_geolocator.MovementThreshold = 1000;
_geolocator.PositionChanged += GeolocatorPositionChanged;

, PositionChanged -
, -
MovementThreshold, ,
, - .
266 19

MovementThreshold . -

.
, ,
PositionChanged.
ReportInterval,
, -
.
, . 19.6
ReportInterval .

19.6.

_geolocator = new Geolocator();


_geolocator.MovementThreshold = 1000;
_geolocator.ReportInterval = 60 * 1000;
_geolocator.PositionChanged += GeolocatorPositionChanged;

ReportInterval , -
, -
.
ReportInterval,
. , -
.
ReportInterval.
:
, .
, -
. -
(. 19.4).
, , ,
(. 19.5). Set
Location.
, .
, ,
, , , -
. -
,
.
10.
267

. 19.4. . 19.5.

Bing Maps SDK


Windows 8.
Bing Maps SDK for Windows
Store apps.
, -
. Bing Maps SDK
vsix-, (. 19.6).
Install, Bing Maps SDK .
LocationApp, , Solution Explorer
References Add Reference... -
, Windows |
Extensions. Bing Maps for C#, C++ or Visual
Basic Microsoft C++ Runtime Package OK. Bing
Maps SDK (. 19.7).
Bing Maps SDK . Bing Maps
SDK , C++, -
Any CPU ( ), -
C#. ,
.
268 19

. 19.6. vsix- Bing Maps SDK

. 19.7. Bing Maps SDK


269

Visual Studio BUILD | Configuration


Manager... Active solution
platform x86 ( Visual Studio 32- -
x86, Windows Store-
) (. 19.8).

. 19.8.

Windows Store
(x86, x64, ARM), -
, Bing Maps SDK.
,
Map.
, , -
( 19.7).

19.7. MainPage Map

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

<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>

<Button x:Name="btnLocation"
Content=" " Grid.Row="0"
VerticalAlignment="Center" HorizontalAlignment="Center"
Margin="10" Click="BtnLocationClick"/>

<bing:Map Grid.Row="1" x:Name="map"/>


</Grid>
</Page>

!
XML bing:
xmlns:bing="using:Bing.Maps", Map: <bing:Map
Grid.Row="1" x:Name="map"/>.

,
(. 19.9).
, ,
. Map

. 19.9. Map
271

Bing,
.
Bing Maps: http://www.bingmapsportal.com/.
,
Credentials Map.
, ( 19.8).

19.8. API Bing Maps

<bing:Map Grid.Row="1" x:Name="map"


Credentials="AsWlUnHbvLgHlLHaRhTZLslewv1QIdGppxOqyL-6He2jxyHvLAjutrcntemUih-
w9"/>


, 19.8, . .

: /
( ZoomIn ZoomOut), "/
" (LayoutChange) ( 19.9).

19.9.

<Page
...
>
<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal"
HorizontalAlignment="Center">
<Button x:Name="btnLocation"
Content=" " Grid.Row="0"
VerticalAlignment="Center" HorizontalAlignment="Center"
Margin="10" Click="BtnLocationClick"/>

<Button Name="ZoomIn" Content="+"


HorizontalAlignment="Center"
VerticalAlignment="Bottom" Height="60" Width="60"
FontWeight="Bold" Padding="0,-9,0,0"/>

<Button Name="ZoomOut" Content="-"


HorizontalAlignment="Center"
VerticalAlignment="Bottom" Height="60" Width="60"
FontWeight="Bold" Padding="0,-9,0,0" />
272 19

<Button Name="LayoutChange" Content="L"


HorizontalAlignment="Center" VerticalAlignment="Bottom"
Height="60" Width="60"
FontWeight="Bold" Padding="0,-9,0,0"/>
</StackPanel>

<bing:Map Grid.Row="1" x:Name="map"


Credentials="AsWlUnHbvLgHlLHaRhTZLslewv1QIdGppxOqyL-
6He2jxyHvLAjutrcntemUih-w9"/>
</Grid>
</Page>

19.10.

19.10.

private void ZoomInClick(object sender, RoutedEventArgs e)


{
if (map.ZoomLevel <= 19) map.ZoomLevel++;
}

private void ZoomOutClick(object sender, RoutedEventArgs e)


{
if (map.ZoomLevel >= 2) map.ZoomLevel--;
}

private void LayoutChangeClick(object sender, RoutedEventArgs e)


{
if (map.MapType == MapType.Road)
map.MapType = MapType.Aerial;
else
map.MapType = MapType.Road;
}

.
GeolocatorPositionChanged -
SetView ( 19.11).

19.11.

void GeolocatorPositionChanged(Geolocator sender, PositionChangedEventArgs


args)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var location = new Location(args.Position.Coordinate.Latitude,
args.Position.Coordinate.Longitude);
273

map.SetView(location, 10);
});
}

SetView . -
, .
,
.
,
, .
MainPage Pushpin ( 19.12).

19.12. Pushpin

private Pushpin _pushpin = new Pushpin();

Pushpin -
,
( 19.13).

19.13. Pushpin

void GeolocatorPositionChanged(Geolocator sender, PositionChangedEventArgs


args)
{
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var location = new Location(args.Position.Coordinate.Latitude,
args.Position.Coordinate.Longitude);

map.SetView(location, 10);

MapLayer.SetPosition(_pushpin, location);
if (!map.Children.Contains(_pushpin))
{
map.Children.Add(_pushpin);
}
});
}

Pushpin
SetPosition MapLayer.
. -
(. 19.10).
274 19

. 19.10. Pushpin


, -
, .


Geolocator.
, .
Bing Maps SDK, -
Bing. , Map,
, .
Taa20

, Windows 8,
,
" ", . . , -
, -
, , -
, ,
.
, ,
: ( -
19), ,
. , -,
,
, .
, , -
, , . -
. , / -
, , -
. API , ,
, .
. -
, .
,
.


-
. , , ,
,
276 20

(. 20.1). , -
, .
,
.

. 20.1.

Blank App LightSensorApp.


( ), -
, MainPage.xaml.
MainPage.xaml. XAML-
20.1.

20.1. XAML- MainPage

<Page
...
>
<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}"
x:Name="LayoutRoot">

<TextBlock x:Name="txtLight" Text=" "


VerticalAlignment="Center"
HorizontalAlignment="Center"
Style="{StaticResource HeaderTextStyle}"/>
</Grid>
</Page>

Grid LayoutRoot,
txtLight.
, , -
, - -
.
LightSensor
Windows.Devices.Sensors. -
277

, LightSensor.GetDefault(). -
null, .
, , ,
. (-
20.2).

20.2.

var lightSensor = LightSensor.GetDefault();


if (lightSensor != null)
{
var val = lightSensor.GetCurrentReading();
}

,
, . -
ReadingChanged LightSensor. C#- -
MainPage 20.3.

20.3.

public sealed partial class MainPage : Page


{
private LightSensor _lightSensor;

public MainPage()
{
this.InitializeComponent();

_lightSensor = LightSensor.GetDefault();

if (_lightSensor != null)
{
_lightSensor.ReadingChanged += LightSensorReadingChanged;
}
}

void LightSensorReadingChanged(LightSensor sender,


LightSensorReadingChangedEventArgs args)
{

}
}

, -
( 20.4).
278 20

20.4.

void LightSensorReadingChanged(LightSensor sender,


LightSensorReadingChangedEventArgs args)
{
var reading = args.Reading;

Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
LayoutRoot.Background = new SolidColorBrush(Color.FromArgb(255,
(byte)(reading.IlluminanceInLux / 2), 0, 0));
txtLight.Text = reading.IlluminanceInLux.ToString();
});
}

,
ReportInterval. -
( 20.5).

20.5.

_lightSensor.ReportInterval = _lightSensor.MinimumReportInterval;

(Resource leak),
, , -
( 20.6).

20.6.

protected override void OnNavigatedFrom(NavigationEventArgs e)


{
if (_lightSensor != null)
{
_lightSensor.ReadingChanged -= LightSensorReadingChanged;
}

base.OnNavigatedFrom(e);
}

-
(g ), -
(. 20.2).
279

. 20.2.


. ,
Z- 1 ( Z , -
, , 1g). ,
, Y- 1.
, .
, , -
1g.
Accelerometer, -
Windows.Devices.Sensors. -
, , ,
GetDefault().
AccelerometerReading,
AccelerationX, AccelerationY AccelerationZ, -
.
, -
, 20.7.

20.7.

public sealed partial class MainPage : Page


{
private Accelerometer _accelerometer;

public MainPage()
{
this.InitializeComponent();

_accelerometer = Accelerometer.GetDefault();

if (_accelerometer != null)
280 20

{
_accelerometer.ReadingChanged += AccelerometerReadingChanged;
}
}

void AccelerometerReadingChanged(Accelerometer sender,


AccelerometerReadingChangedEventArgs args)
{
//
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
AccelerometerReading reading = args.Reading;

var x = reading.AccelerationX;
var y = reading.AccelerationY;
var z = reading.AccelerationZ;
});
}
}

"" . ,
, (. 20.3).

. 20.3.

, ,
( ).
, . -
, .
. . 20.4 -
, , . -
, .
, -
, , . -
281

,
( 20.8). -
Shaken.

. 20.4. , ,

20.8.

public MainPage()
{
this.InitializeComponent();

_accelerometer = Accelerometer.GetDefault();

if (_accelerometer != null)
{
_accelerometer.ReadingChanged += AccelerometerReadingChanged;
_accelerometer.Shaken += AccelerometerShaken;
}
}

void AccelerometerShaken(Accelerometer sender, AccelerometerShakenEventArgs


args)
{

.

. , , ,
. -
, , -
, .
282 20

. -
. -
Gyrometer ( 20.9).

20.9.

public sealed partial class MainPage : Page


{
private Gyrometer _gyrometer;

public MainPage()
{
this.InitializeComponent();

_gyrometer = Gyrometer.GetDefault();

if (_gyrometer != null)
{
_gyrometer.ReadingChanged += GyrometerReadingChanged;
}
}

void GyrometerReadingChanged(Gyrometer sender,


GyrometerReadingChangedEventArgs args)
{
//
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
GyrometerReading reading = args.Reading;

//
var x = reading.AngularVelocityX;
var y = reading.AngularVelocityY;
var z = reading.AngularVelocityZ;
});
}
}

( . incline ) ,
.
Windows 8, . .
.
, ( -
283

)
Sensor Fusion (. 20.5).
, .

. 20.5. Sensor Fusion

. -
, .

.
: Roll (), Pitch () Yaw
(),
(. 20.6).

. 20.6. Roll, Pitch Yaw


284 20

, ( -
).
. 20.7 Roll, Pitch Yaw .

. 20.7. Roll, Pitch Yaw .


( Wikipedia: http://en.wikipedia.org/wiki/Flight_dynamics_(fixed_wing_aircraft))

, . Z (Yaw)
, .
X (Pitch) , , . -
Y (Roll) .
.

( -
,
). - -
. -
DirectX,
.

. -
,
.
. .
Blank App InclinometerApp.
XAML- MainPage 20.10.

20.10. XAML- MainPage

<Page
...
>
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<StackPanel Orientation="Horizontal"
HorizontalAlignment="Center">
285

<TextBlock x:Name="txtRoll" Margin="5" FontSize="60"/>


<TextBlock x:Name="txtPitch" Margin="5" FontSize="60"/>
<TextBlock x:Name="txtYaw" Margin="5" FontSize="60"/>
</StackPanel>

<Canvas VerticalAlignment="Stretch"
HorizontalAlignment="Stretch">
<Rectangle x:Name="rectMain" Fill="Red" Width="100"
Height="100" Canvas.Left="500" Canvas.Top="300"/>
</Canvas>

</Grid>
</Page>

StackPanel , -
Roll, Pitch Yaw . -
Canvas rectMain, .
C#- .
"" Inclinometer.

( 20.11).

20.11.

public sealed partial class MainPage : Page


{
private Inclinometer _inclinometer;
private DispatcherTimer _dispatcherTimer;

public MainPage()
{
this.InitializeComponent();

_inclinometer = Inclinometer.GetDefault();

if (_inclinometer != null)
{
uint reportInterval = _inclinometer.MinimumReportInterval >
16 ? _inclinometer.MinimumReportInterval : 16;

_dispatcherTimer = new DispatcherTimer();


_dispatcherTimer.Tick += ProcessCurrentReading;
_dispatcherTimer.Interval =
TimeSpan.FromMilliseconds(reportInterval);
_dispatcherTimer.Start();
}
}
286 20

private void ProcessCurrentReading(object sender, object args)


{
InclinometerReading reading = _inclinometer.GetCurrentReading();

if (reading != null)
{
//
var top = (double)rectMain.GetValue(Canvas.TopProperty);
var left = (double)rectMain.GetValue(Canvas.LeftProperty);

rectMain.SetValue(Canvas.TopProperty,
top (reading.PitchDegrees / (double)4));
rectMain.SetValue(Canvas.LeftProperty,
left (reading.RollDegrees / (double)4));

//
txtRoll.Text = String.Format("Roll: {0,5:0.00}",
reading.RollDegrees);
txtPitch.Text = String.Format("Pitch: {0,5:0.00}",
reading.PitchDegrees);
txtYaw.Text = String.Format("Yaw: {0,5:0.00}",
reading.YawDegrees);
}
}
}


. , -
ReadingChanged .
.

.
, . -
, .

Sensor Fusion.
,

. Compass.
. ,
, -
, , .
287


,
,
. , .

( ), VSM (Visual
State Manager), ApplicationView.Value (-
, ). -
9. -
.
SimpleOrientationSensor.
20.12.

20.12.

SimpleOrientationSensor orientation = SimpleOrientationSensor.GetDefault();

if(orientation!=null)
{
var currentOrientation = orientation.GetCurrentOrientation();
}

OrientationChanged
SimpleOrientationSensor.
, , . 20.1.

20.1. ,

NotRotated
Rotated90DegreesCounterclockwise 90
Rotated180DegreesCounterclockwise 180

Rotated270DegreesCounterclockwise 270

Faceup
Facedown

, -
View ApplicationView: FullScreenLandscape,
FullScreenPortrait, Filled Snapped.
288 20


, , "" .
,
OrientationSensor.
.

, .

.
. -
GetDefault -
. null.
null .
-
. .
, , ,
, , -
Sensor Fusion .
, -
.
Taa21

,
. , , -
, .
,
, . -
- .
,
. , , ,
, . -

, , -
.
. .
, . . -

, , ,
.


, , , ,
, -
, .

(Internationalization, i18n), -
. ,
.
.
, -
.
290 21

, -
, . -

, . -
, -
.
,
, . ,
-
, .
Windows Store- .NET- Windows Phone-
. , Windows 8, ,
, . -
, .

Windows Store-, Windows-


Web-, (Culture).
, , :
. , .
, "en-US".
"en-GB". "ru-RU".
, , -
. , "ru".
, .
. -
CultureInfo,
System.Globalization. CultureInfo , .
, NativeName, "ru-RU"
" ()" DisplayName ( "Russian").
. ,
( 21.1) "en-US"
"Sunday, September 30, 2012".

21.1.

//Sunday, September 30, 2012


var date = DateTime.Now.ToString("D");

"ru-RU" "30 2012 .".


( 21.2).
291

21.2.

var cultureInfo = new CultureInfo("ru-RU");


// 30 2012 .
var date = DateTime.Now.ToString("D", cultureInfo);

, (-
21.3).

21.3.

const double money = 127800.30;


var strMoney = money.ToString("C");

"ru-RU" strMoney 127 800,30 ., "en-


US" $127,800.30, "de-DE" 127.800,30 "it-IT" 127.800,30. -
, ,
, . ,
. . -
, .
,
,
CultureInfo.InvariantCulture, ,
- .
, .


( Package.appxmanifest).
Default language (. 21.1).
, , -
. ,
"ru-RU". , , -
"en", .
( ) -
PrimaryLanguageOverride ApplicationLanguages
( 21.4).

21.4.

ApplicationLanguages.PrimaryLanguageOverride = "de-DE";

Windows 8 Windows
, ( -
292 21

. 21.1.

) . Windows 8 ,
. , -
, , -
. , , ( )
.
(Control Panel) Control
Panel | Language (. 21.2).

. 21.2.

, . Windows Store-

GlobalizationPreferences.Languages.
( -
. " " ), -
293

, , , -
.
-
, , -
( ), -
.
, -
, , .


Windows Store- ( , WPF, Silverlight
Windows Phone-) XAML-
. XAML-, , -
, . Windows 8
,
XAML.
, "Hello!" "World!"
( 21.5).
, , .

21.5.

<StackPanel>
<TextBlock Text="Hello!" Width="400"
HorizontalAlignment="Left" Margin="10"
Style="{StaticResource HeaderTextStyle}" />
<TextBlock Text="World!" Width="400"
HorizontalAlignment="Left" Margin="10"
Style="{StaticResource HeaderTextStyle}" />
</StackPanel>

: Width,
HorizontalAlignment Margin. -
(x:Uid) .
Hello World ( 21.6).

21.6.

<StackPanel>
<TextBlock x:Uid="Hello" Text="Hello!" Width="400"
HorizontalAlignment="Left" Margin="10"
Style="{StaticResource HeaderTextStyle}" />
294 21

<TextBlock x:Uid="World" Text="World!" Width="400"


HorizontalAlignment="Left" Margin="10"
Style="{StaticResource HeaderTextStyle}" />
</StackPanel>

,
. Languages ( -
) : en-US ru-RU. -
Resources.resw, Resource File (.resw)
(. 21.3).

. 21.3.

resw .NET-
resx: , resw- -
. en-US
, . 21.1 (. 21.4).

21.1. en-US


Hello.HorizontalAlignment Left
Hello.Text Hello!
Hello.Width 400
World.Text World!
295

. 21.4. en-US

ru-RU . 21.2.

21.2. ru-RU

Hello.HorizontalAlignment Right
Hello.Text !
Hello.Width 500
World.Text !

. -
. ,
.
, "!", -
, "!". "Hello!",
, "World!".
Windows 8 -
( ).
, , .NET
Framework, .
Windows 8 .lang-.
, ru-RU -
: Resources.lang-ru-RU.resw.
296 21

-
:
 Resources.lang-de-DE.resw;
 Resources.lang-de-AT.resw;
 Resources.lang-de-CH.resw.
, ,
: Resources.resw.
, , , -
, Languages,
, Localization. .

. , "en",
"ru", "de". -
, -
, . -
"en-US" .lang-en-US .
"de-DE" .lang-de-DE.
, ,
, ? -
,
.
:
 Languages\de\Resources.lang-de-DE.resw;
 Languages\de\Resources.lang-de-AT.resw;
 Languages\de\Resources.lang-de-CH.resw.
:
 Languages\de-DE\Resources.resw;
 Languages\de-AT\Resources.resw;
 Languages\de-CH\Resources.resw.


, , .
, ,
Images\logo.png, ,
:
 Images\en\logo.png;
 Images\ru\logo.png
( 21.7).
297

21.7. XAML-

<Image Source="Images/logo.png" />

9, -
, . -
-
:
 Images\ru\logo.scale-100.png;
 Images\ru\logo.scale-140.png;
 Images\ru\logo.scale-180.png.
(contrast-white
contrast-black).
( High
Contrast PC settings | Ease of Access):
 Images\ru\contrast-black\logo.scale-100.png;
 Images\ru\logo.contrast-black_scale-100.png.



. , -
ErrorMessage,
( 21.8).

21.8.

var resourceLoader = new ResourceLoader();


var message = resourceLoader.GetString("ErrorMessage");

.
-
Resources.resw. , -
Errors.resw.
Errors.resw, ResourceLoader -
( 21.9).

21.9. Errors.resw

var resourceLoader = new ResourceLoader("Errors");


var message = resources.GetString("ErrorMessage");
298 21

, -
, . ,
Errors.resw LocalizationLibrary.dll, -
( 21.10).

21.10.

var resourceLoader = new ResourceLoader("LocalizationLibrary/Errors");


var message = resources.GetString("ErrorMessage");


Windows Store- .
(
):
 ApplicationDisplayName;
 ApplicationShortName;
 ApplicationDescription.
, -
.

ms-resource:, , ms-resource:ApplicationDisplayName (. 21.5).

. 21.5.
299

, , -
, .

Windows Store-
. , , -
,
,
.
Windows Store-
, . .
. ,
. , -
, Windows 8, -
.
Taa22


Windows 8
Windows 8, Microsoft (,
Windows Phone, Xbox 360 Visual Studio 2012),
, -
. , -
.
-
, - -
. ,
, , -
, , ,
.
, ,
, , ,
.

Windows 8
, , ,
Windows Phone Windows 8,
"Metro"-. "Metro" -
, -
Windows Phone Windows 8.
, ,
(, , -
, "Avalon", Windows
Presentation Foundation, WPF), "Metro" -
, "Windows". -
Windows 8 301

Windows,
Windows, Windows 8.
, , ,
, , -
, , -
,
.
Microsoft , -
, Windows Media Center (. 22.1).

. 22.1. Windows Media Center

Microsoft Zune
( ), (Zune Windows
Zune.net ) (. 22.2 22.3).
, Windows
Zune.net Silverlight Cosmopolitan.
, Windows Phone 7,
-
.

Microsoft, -
. ,
.
, ,
, . ,
302 22

. 22.2. Zune HD

. 22.3. Zune Windows


Windows 8 303

Windows, ,
Microsoft.
 (Bauhaus) (, ,
), , -
,
.
 (International Typographic Style,
Swiss Design) , -
, ( , -
) (
). ,
.
 (Motion Design) -
( ), , -
, -
""
.
, , , , -
, ,
, -
, , Windows 8 Windows
Phone.

Windows
:
1. .
2. .
3. - .
4. .
5. .
.


, . ,
, ,
, , , -
, .
, - ,
, , -
.
304 22

, , , -
, - -
.
. . , -
, , , -
- , -
.
, (
).
,
(Information Architecture, IA). , -
, ,
, ,
, .
,
, , , .
,
: ,
.
, -
.
,
, .
( Windows 8
2020 px 55 px) (. 22.4).

. 22.4.


, -
,
.
Windows 8 305

,
-
, ( -
, ).
, , ,
. -
, , ,
,
(. 22.5).

. 22.5.

, , Visual Studio, -
: 42 pt, 20 pt, -
11 pt, 9 pt.
, , .
. ,
. ,
.
, , -
, , , -
, ,
"". , ,
"" - Windows 8
. ( , "" Mac OS X,
306 22

, -
, .)
"" . . (
?) , ,
, iOS, . -
, , , , -
. ,
( ),
/ Windows
.
(
) ,
, .
, Windows ( Windows
Phone) , -
. .
Windows 8 Cocktail Flow (. 22.6).

. 22.6. Coctail Flow Windows 8

, , -
.
,
, ,
.
Windows 8 307

"" -
. . -
. , -
. .

, , , -
.


Windows 8, -
, , ,
. , -
, ,
, .
, ( -
),
.
. (, , ),
, , -
, (, ) -
.
!
" " ,
.

(Chrome).
, , ,
(, ,
, ). -
, -
.
:
 ;
 ;
 .
.
 . ,

, -
. "".
, (. 22.7).
308 22

. 22.7. Bing Weather

, , (
), , , ,
( , ).
 . -
: ,
, , -
. , -
() .
,
,

" ", "" -
. .
,
.
.
, " " (. 22.8).
, , - -
: , ,
, (
)
.
- , -
. Windows 8
.
Windows 8 309

. 22.8. ""

 .
- , -
. . , , ,
,
.
,
. - , -
, , -
(),
, , " ".
, - ( -
). Windows 8 ?
-, , -
"-", -
, ,
. -
-
.
-, ,
(, ,
), , -
, , -
(. 22.9).
310 22

. 22.9. USA Today

, -
,
, .
, .
 , -
, , , -
, , .

23. ,
,
. , , ,
.
, .
 , -
. (, ), -
, , .
.
.
Windows
. ,
, .
. , " -
Windows 8 311

", , , ,
.

. .

-
, -
,
, .
, -
, "".
, -
.
. , , , -
(. 22.10).

. 22.10. ""

, ,
-
, , , . ,

( ).
, ,
Segoe UI,
312 22

Windows 8.
, ,
.
, , -
. , , ,
"" , ,
, , -
.

; , -
, , -
.

. -
, , -
,
.
, ,
, -
. , , -
, -
.
,
,
, , ,
, ().
, Win-
dows 8.
,
(Semantic Zoom), 8.
, , ,
"" ,
, , , , -
(. 22.11 22.12).
"", -
(/). ,
-
, -

. , , -
, ,
, , -
(, , . .),
, , .
Windows 8 313

. 22.11. "Contoso News"

. 22.12. "Contoso News"

"". -
( ). ,
Web-,
.
, "" -
.
, .
-
.
314 22

, - -
. -
(, ),
, , , , -
, ,
.
, -
"".
: -
, - ,
, "".
,
. ,
"" ,
, , ,
. , -
.


, ,
. -
, -
, , -
.
,
, ,
, , .


, "" , , .

. , -
.
,
. , ,
,
, .
, ( ) -
, ,
, , - .
, "", -
, -
.
Windows 8 315

Windows 8,
, , , . -
.
, -
. -
, , - (. 22.13).

. 22.13. Windows 8

, , Windows 8
" ", ,
, , (
7 ),
, -
.
. -
.
Windows 8 (
, ).

, -
, , -
, , ,
"-" ( -
), , ,
.
-
, , Windows 8
316 22

(Animation Library)
Windows.UI.Xaml.Media.Animation XAML/C#
WinJS.UI.Animation HTML/JS.
"". , - "", -
. , "" -
, ,
.
10, Windows Store-,
, , -
.
, , , - .
, " -
" , .
( ).
. , -
, , ,
"". , -
, ,
, -
. "" -
.
, . . -
, , , -
. ,
,
.
"".
, , -
, -
, .
, . ,
,
, , ,
, .

"" , -
.


, , , -
, , . ,
, , .
Windows 8 317

, Windows Store, -
, .
. , , . -
,
-.
,
, , -
/ .
, :
,
, , , , ,
.
, -
( , ).
Windows-
, -
.
, , : Windows 8
Windows RT. , Windows Store, -
, , ARM-
Intel/AMD- .


, -
GPU (" "), CPU (), , -
, .

,
, -
. , -
, . ,
.
, ,
.
.
. Windows 8 "",
.
,
.
. 1315 .
-
,
.
318 22

(Sharing) (, -
. .).
, Windows 8
"-" " ".
, : , -
, , .
, .
, -
,
.
, , ,
. , -
, ,
.
(Mail),
, "",
(People), -
. .
-
.
, -
, , , , , . -
,
, .
.
.
. , " ", -
. ( Visual Studio,
Adobe Photoshop), (
http://design.windows.com) Expression Blend (
XAML HTML) -
.

,
Windows:
1. .
, . "".
2. . ,
, .
Windows 8 319

3. - .
, , -
.
4. . -
, , .
5. . Windows Windows -
, , -
.
Taa23

,


Windows 8
, , ,
, Windows 8 Windows
Phone, -
(UX UI).
( ) -
Windows 8 -
, Web-. "-
" ,
,
.

, Windows 8 (
, C#, Visual Basic, JavaScript C++), -
, ( ) , . , ,
Windows 8 , -
.

, , -
, -
, -
( )
.
,
. , -
, . : -
.
, Windows 8 321


Windows 8 ( -
, Windows Phone, -
, - ) -
, .
,
, , -
.
, -
:
1. .
2. .
3. .
4. .
5. .

1.
:
, ( ) -
.
( -
), . , -
(
), :
 ?
 ?
 , ?


, :
?

? ,
, , ?
,
-
?
, / -
, .
322 23

. -

.

, ?

? -
, , 1015 ? , ,
, , ?
-
.
, . " ", -
, ,
-
, , .
-
.
?


, ?

, , ,
, , ? ,
,
, ,
?
, , -
! ? ? ?
?
, -
, , , , ,
(), -
, .
- :
 ?
 , -
, :
?
?
?
, Windows 8 323

?
- ?

. , . 23.1.

. 23.1.

-
. -
,
. , -
,
, .
, - (
., . .), () -
. , -
, (, ,
, ),
(. 23.1).
, .

23.1.

. . .
. . .
. . .
324 23

2. ?
, , , -
, .
, -
.
, , , -
(, "" "
").
, ,
( "best at
statement"). "Best at statement" ,
, , .
, :
" ".
" ".
1) , 2) 3) -
. ,
.
, , "
", ,
, , , , -
. , -
, , - -
( -
).
: " online-
" , , , ( ) -
,
, ,
, ,
( ,
), .
, , -
(, ) -
: .
!
.

- ,
- , ,
, Windows 8 325

. ,
: , -

.
, -
: " -
".
,
, , -
( ).
Best = focus. ,
, .

3.
, -
, -
.
, "", (
" "), -
, .
: ?
:
 ?
 ?

. ,
, .
( /),
, ( -
,
).

(. 23.2).
, "" , -
.
, .
-
, ,
. , , -
326 23

-
( )
(. 23.3).

. 23.2.

. 23.3.

/ ,
. ,
"best at statement" (. 23.4).
 , ,
, "" (
, , ), -
, .
 , , ,
, ,
( ),
.
, Windows 8 327

 , /
, , ,
. . .
 , ,
, - , -
.

. 23.4.

- -
, -
, ,
.
, , . -
,
.
: 1) -
; 2) ;
3) .
,
- , , -
, ( -
, ).
, "" ,

.
, , -
.
. ,
- , ( ) -
. , -
328 23

() . ,
,
.
"" ,
.
(-
) .
-
.
., , " 7". " -

", . ( -
), Movie Meeting,
-
.


8 . , . .
.
. , , -
.

Movie Meeting
.
( , ). ,
, , -
, -
(. 23.5).
, ,
. , , .
,
.


("best at statement").
. -
, , .

, ,
-
(content/features provider 
scenario provider).
, Windows 8 329

. 23.5.

4.
, ,
-
- . , -
. ,

.
, -
, -
.
( ).
. 23.6.
, , -
Windows 8,
: , ,
, -
, (, , , . .).
: , -
, , ,
-
Windows 8.
330

. 23.6.
23
, Windows 8 331

. , .
, ,
. ,
, ,
, , ,
. ,
.
, "" ,
/. - -
():
, .
, -

.
Movie Meeting
:
1. : .
2. : .
3. .
4. .
5. : .
6. : .
7. : , , .
8. + : .

, ,
, -
, ( )
(. 23.7).
"" , -
(Actions).
, - ,
-,
.
, ,
Windows 8.

"
Metro" : http://msdn.microsoft.com/ru-RU/library/windows/
apps/hh761500.
332 23

. 23.7.

,
.
Windows 8. ( ),

. -
, , . .
Susan Weinschenk
"The Psychologists View of UX Design"1: "People will do the least amount of work
possible to get a task done. It is better to show people a little bit of information and let
them choose if they want more details. The fancy term for this is progressive disclosure."
" -
.
, . progressive
disclosure ( )."
, ,
.
, ,
( , ,
).
Windows 8 : -
. , Master-

1
http://uxmag.com/articles/the-psychologists-view-of-ux-design.
, Windows 8 333

Details, , , "",
.
,
,
, .
,
, .
510 ,
, , ,
( ) .
, , -
"", (
) .
, ,
, , .
, -
(. 23.8).

. 23.8.

,
. ,
.
334 23

-
.
(3 . 23.9) -
"" (4 . 23.9). -
(-
5 . 23.9).

. 23.9.

-
.
-
(
, Navigation Bar),
, ,
(. 23.10).
, ,
.
, -
(, ), IM, , -
. ., -
.
-
. , Bing News
,
, -
(. 23.11 23.12).
(Semantic Zoom). Windows 8
, -
, Windows 8 335

. 23.10.

(, ). -
,
, ,
(. 23.13).
, -
(. 23.14).
( ) , -
.
, - .
, -
,
.
, (. 23.15).
336 23

. 23.11. Bing News

. 23.12. Bing News


, Windows 8 337

. 23.13. ,

. 23.14.

. 23.15.
338 23

(Pivots), , Windows Phone,


Windows 8. , Windows
Store, (. 23.16). Overview, Details
Reviews .

. 23.16. Windows Store

" ", -
, , Windows Phone:
()
- . , -
, () .


. ,
, .
, ,
, (Snapped Mode),

. (-
, ) -

.

Windows 8 , -
.
, Windows 8 339

, Movie Meeting, -

:
 .
 .
 .
-
, ( /) -
.

.
, ,
, (. 23.17):
 " " .
 " //" -
""
.
 " "
( , ).

. 23.17.

, -
(Landing Page) , ,
. , -
.
() -
( ) -
, ,
, , -
/ -
.
-
(. 23.18).
,
, (. 23.19).
340 23

. 23.18.

. 23.19.
, Windows 8 341

-
.
, , , -
:
 () ;
 ( ,
, , -
);
 ;
 /;
 , ( ), -
, ;
 , ;
 ;
 -
;
 ;
 ( -
).

, , ,

.
,
, , .

(. 23.20).
. 23.21 , .
:
 ();
 ()
, . . " ";
 ,
( , ),
.
, .
342

. 23.20.
23
, Windows 8 343

. 23.21.
344 23

5.
, ,
.
() , , !
, ( -
: , ).
-
, ,
,
.
, -
.
, .
,
. " ", -
. . (. 23.22).

. 23.22.

(. 23.23).
, (-
) , , .
. -
, .
,
.
-
. , -
-
(. 23.24).
, Windows 8 345

. 23.23.

. 23.24.

. 23.24 -
.
:
 (
), . . .
 ,
, . . .
( , , )
: ,
.
346 23

, -
( ) . ,
, Web- . -
Lenovo, ,
(. 23.25).

. 23.25.

-
.
, .
Windows 8 ,
. 23.26.
, ? , , :
( , )
"".

. 23.26. Windows 8
, Windows 8 347

, , ,
. Windows 8 :
 + ;
 .
, , -
, (. 23.27).

. 23.27.

,
( ),
(
).
,
, , .
, ,
: (
) , , . -
() "",
.
"-
" (Charms), , .
, "-" -
. -
:
 ,
Search ( inline-, -
348 23

, , -
).
 ,
, -
Share. (
, .)
 , Settings. -
, Windows Store
, -
(,
).
 ,
(, )
"" (Devices).
-
, .

-
. , "-
".

() -
, ( ).
-
( , ) , -
.
, "" -
. :
.
( )
(. 23.28).
, ( -
), (), ( -
) .
, .
. (
, ) (. 23.2).
- , -
:
 ?
 ?
""
, .
, Windows 8 349

23.2.



(Full & Fill Mode) (Snapped Mode)

( - 03 02
!)
07 (3+4, 2+5) 05
, ,

. 23.28.

" " -
.
, ( ) -
// . .
, ,
, :
 , (),
, ?
 ?
 ?
 ?
 , , .
350 23

 -
. 23.2.
Movie Meeting. -
.
-
? , . , -
,
.
()? :
 (. 23.29):
;
( Web-).

. 23.29.

 (. 23.30):
- , ;
(, );
/;
;
.
( )?
:
 :
;
;
;
;
.
, Windows 8 351

 :
.
, , ""
. -
.

. 23.30.

-
.
(. 23.31):
 , -
.
 , (,
- ).

. 23.31.
352 23

 ,
.
:
 -
.
 -
.

. -
.
(. 23.32):
 ,
, .
 - , -
, -
(Invite+) .
 / . ,

. ,
, -
.
 , .
"" .
:
 ,
.

. 23.32.
, Windows 8 353

. ,
,
, .

, -
, ,
, -
, -
.
,
:
 .
 - ,
.
 ,
.
 ?
 "best at statement".
 - ,
.
 .
 - , .
 ,
-
.
 .
 .
 , -
. -
, , ,
.
 .
 , .
, , ,
.
, . -
, ( , ,
).
Taa24


Windows Store
Windows Store Windows 8 (. 24.1),
,
, Windows 8.
Windows 8 (Developer Preview,
Consumer Preview Release Preview) Microsoft
16 , 7 Release Preview.
Windows 8
7 , ,

. 24.1. Windows Store


Windows Store 355

Windows Store , -
, , , .
Windows Store, -
. $49 -
$99 . -
DreamSpark (http://www.dreamspark.ru).
Windows Store
(). , ,
. ,
, -
, . , -
, .
,
. -
, ,
Windows Store . -
, .
, Windows Store,
.
: -
. API
- (Trial) : (-
) ( -
). - , -
.
.
Windows Store (In-App
Purchases) API. , -
.
.
Windows Store -
. -
,
Microsoft.
, . , , -
$25 000, 70/30: 70% , 30% Microsoft.
$25 000, 80%
.
. Microsoft
"" Microsoft Advertising
SDK .
.
356 24

Windows Store
Windows ,
(. 24.2).
, Windows 8, -
, .
Windows Store : -
(, , . .) -
.
. . 24.3 "".

. 24.2.

. 24.3. ""
Windows Store 357

, Windows Store , ,
-, " ".
, , -
: , . . (. 24.4).

. 24.4.

. 24.5.
358 24

,
(. 24.5).

Windows Store
, , Windows 8. :
 Windows;
 Windows Pro;
 Windows RT.
PC
(x86/x64),
ARM, , , -
. , Windows RT, , , .
Windows Windows Pro Windows-
Windows Store-. ,
"Designed for Windows 7" - ,
Windows 8, .
Windows RT . ARM-
Windows-
( Windows RT ).
, Windows Store- Microsoft
Windows/Windows Pro, Windows RT.
Windows Store-, C++ -
(Native) ,
Windows Store. ,
Windows RT, , -
Windows Store.
, Windows RT ARM-
MS Office, .
, Windows Store-,
, Windows 8
.

Windows Store
Windows Store :
1. Microsoft Account ( Live ID). Microsoft
Account, . Microsoft
Account .
. , Microsoft Account ,
/ .
Windows Store 359

2. , , -
. ,
- ,
. -
,
.
3. , , -
Windows Store.
, Microsoft Account.
, . -
Windows:
 DreamSpark;
 BizSpark;
 MSDN ( Visual Studio Professional, Test Professional,
Premium Ultimate).
MSDN ,
"Subscription Benefits" MSDN-
"Windows Store developer account". -
() Windows Store. -
610 .
Windows Store :
https://appdev.microsoft.com/StorePortals/Account/Signup/Start.
Microsoft Account. -
Windows ( ) Microsoft Account
(Security Code).
. -
"" Microsoft Account.
.
, "I trust this PC"
(-
Cookies).

(. 24.6).
, , -
, .
, . . -
.
. Individual (
), Company ( ).
, . .
,
360 24

. 24.6.

. ,
Windows- . ,
, -
:
 enterpriseAuthentication Windows -
;
 sharedUserCertificates
- ;
 documentsLibrary -
, , .
. -
Windows Store. , ,
,
Windows Store. , -
" ".
,
, . , ,
, .
-
.
, , -
, .
 Web- Web-,
. ,
Windows Store 361

, ,
.
 (Publisher Display Name) , -
-
. , -
-
. , . .
Windows Store. -
, ,
.
, -
. -
,
.
-
.
 VAT ID ( )
(), .
 (Approver) Microsoft -
, -
, Approver info.
Approver info -
.
, -
Microsoft, Symantec GeoTrust.
, .
,
(, , ). -

.
.
(), . -
.
!
, !

,

Windows Store.
-
. -
-
362 24

. ,
.
. -
.
https://appdev.microsoft.com/
StorePortals/en-us/Home ,
, , , .
Purchase ().
, Dashboard ( -
) (. 24.7).
! !

. 24.7.


.
. :
 Windows ,
.
 .
Windows Store 363

 , -
, , , -
.
Submit an app.
App name. App name -
. Reserve
app name.
,
. 21
. .


Windows Store
Windows Store,
Visual Studio Express STORE | Create App Packages...
PROJECT | Store | Create App Packages ... Visual Studio.

. 24.8.
364 24

Yes Do you want to


build packages to upload to the Windows Store? Sign
In, Microsoft Account -
.
-
. , -
C++, (. 24.8).
Create.
Windows Store (. 24.9).

. 24.9.

Windows Store .
, , , -
,
. Visual Studio Windows App Certification Kit
(WACK), ,
. -
, .
WACK ,
Windows Store 365

. -
Windows Store WACK (. 24.10).
WACK, -
Windows Store. WACK -
(. 24.11).
Windows Store. Dashboard,
Submit an app. -
, . . .

. 24.10. Windows App Certification Kit

. 24.11. WACK
366 24

-
, -:
( ) . -
- .
, - -
, "" -
.

LicenseInformation. -
CurrentApp,
CurrentAppSimulator ( 24.1). CurrentApp ,
Windows Store.

24.1.

//var licenseInformation = CurrentApp.LicenseInformation;


var licenseInformation = CurrentAppSimulator.LicenseInformation;

CurrentAppSimulator
WindowsStoreProxy.xml, :
<__>\Microsoft\Windows Store\ApiData
WindowsStoreProxy.xml 24.2.

24.2. WindowsStoreProxy.xml

<?xml version="1.0" encoding="utf-16"?>


<CurrentApp>
<ListingInformation>
<App>
<AppId>89644424-d0be-44ae-bb73-f38bf7037dd5</AppId>
<LinkUri>http://apps.windows.microsoft.com/app/89644424-d0be-44ae-bb73-
f38bf7037dd5</LinkUri>
<CurrentMarket>en-US</CurrentMarket>
<AgeRating>12</AgeRating>
<MarketData xml:lang="en-us">
<Name>Trial management full license</Name>
<Description>Sample app</Description>
<Price>4.99</Price>
<CurrencySymbol>$</CurrencySymbol>
</MarketData>
</App>
</ListingInformation>
<LicenseInformation>
<App>
Windows Store 367

<IsActive>true</IsActive>
<IsTrial>true</IsTrial>
<ExpirationDate>2012-12-01T01:00:00.00Z</ExpirationDate>
</App>
</LicenseInformation>
</CurrentApp>


WindowsStoreProxy.xml. XML-
, LicenceInfo.xml (. 24.12).

. 24.12.
LicenceInfo.xml

LicenceInfo.xml WindowsStoreProxy.xml.
LicenceInfo.xml -
WindowsStoreProxy.xml ( 24.3).
LicenceInfo.xml ( AppId). -
Packaging.
368 24

24.3. WindowsStoreProxy.xml
LicenceInfo.xml

var folder = await ApplicationData.Current.LocalFolder.CreateFolderAsync(


"Microsoft\\Windows Store\\ApiData", CreationCollisionOption.OpenIfExists);

var file = await


Package.Current.InstalledLocation.GetFileAsync("LicenceInfo.xml");
var newfile = await folder.CreateFileAsync("WindowsStoreProxy.xml",
CreationCollisionOption.ReplaceExisting);
await file.CopyAndReplaceAsync(newfile);


WindowsStoreProxy.xml. IsTrial
LicenseInformation , -. -
- , ,
( 24.4).

24.4. -

//var licenseInformation = CurrentApp.LicenseInformation;


var licenseInformation = CurrentAppSimulator.LicenseInformation;

if (licenseInformation.IsActive)
{
if (licenseInformation.IsTrial)
{
var remaining = licenseInformation.ExpirationDate DateTime.Now;
}
else
{
// ...
}
}


CurrentApp CurrentAppSimulator
-, (In-App
Purchases). .

Windows Store ,
. ,
. -
Windows Store 369

, Windows App Certification


Kit (WACK).
, -
, -, .

(In-App Purchases). ,
. -
.
370 24
poe
poee1

XAML

XAML (eXtensible Application Markup Language,


[]) . -
XAML XML, -
. , , XAML, -
, , -
. XAML-
, C# (
). Foo, 1.1.

1.1. Foo

namespace FooNamespace
{
public class Foo
{
public string SomeText { get; set; }
}
}

Foo SomeText.
C# ( 1.2).

1.2. Foo C#-

Foo foo = new Foo();


foo.SomeText = " ";

Foo XAML- ( 1.3).


374 1

1.3. Foo XAML-

<Foo SomeText=" " />

1.3 .
XAML-, C#,
. C#-
using.
, FooUser Foo,
( 1.4).

1.4. FooUser

using FooNamespace;

namespace SomeNamespace
{
public class FooUser
{
public FooUser()
{
Foo foo = new Foo();
foo.SomeText = " ";
}
}
}

FooUser Foo , -
. XAML-
. XML xmlns.
XAML- XML
Windows Runtime . 1.5
Foo
FooNamespace. ,
, -
.

1.5.

<FooNamespace:Foo SomeText=" "


xmlns:FooNamespace="using:FooNamespace" />

!
-
, .
XAML 375

Windows Store- ( 1.6).

1.6. Windows Phone

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

<Grid Background="{StaticResource
ApplicationPageBackgroundThemeBrush}">

</Grid>
</Page>

( 1.7) -
"x" ( 1.8).

1.7.

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

1.8. "x"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

XML, . -
, , -
Windows Runtime.
.
,
Grid, StackPanel , .
-
- .
"x" (x:Name), (x:Key),
(, x:Null -
NULL).
XAML- , -
, .
376 1


XAML XML XAML .
,
. 1.3 SomeText .
( 1.9).

1.9.

<FooNamespace:Foo xmlns:FooNamespace="using:FooNamespace">
<FooNamespace:Foo.SomeText>

</FooNamespace:Foo.SomeText>
</FooNamespace:Foo>

,
.
( 1.10).

1.10.

<Grid x:Name="ContentPanel"
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="" Foreground="Yellow" Background="Blue"/>
</Grid>

"", (Foreground=
"Yellow")
(Background="Blue").
Foreground Background (-
1.11).

1.11.

<Grid x:Name="ContentPanel"
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="">
<Button.Foreground>
<SolidColorBrush Color="Yellow"/>
</Button.Foreground>
<Button.Background>
<SolidColorBrush Color="Blue"/>
</Button.Background>
</Button>
</Grid>
XAML 377


C# ( 1.12).

1.12.

Button newButton = new Button();


newButton.Content = "";
newButton.Foreground = new SolidColorBrush(Colors.Yellow);
newButton.Background = new SolidColorBrush(Colors.Blue);
ContentPanel.Children.Add(newButton);

,
Text ( ), Content. -
, . -
.
, -
CheckBox, RadioButton TextBox. RadioButton
( 1.13, . 1.1).

. 1.1.

1.13.

<Button>
<Button.Content>
<StackPanel>
<CheckBox Content="CheckBox"/>
<RadioButton>
<StackPanel>
<Button Content=" 1" />
<Button Content=" 2" />
<Button Content=" 3"/>
378 1

</StackPanel>
</RadioButton>
<TextBox />
</StackPanel>
</Button.Content>
</Button>

-
. Content.
<Button.Content> . -
1.13 <RadioButton.Content> .



, . XAML-
.
, Foreground FontSize (-
1.14).

1.14.

<Style TargetType="Button" x:Key="buttonStyle">


<Setter Property="FontSize" Value="48"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Yellow"/>
</Setter.Value>
</Setter>
</Style>

,
.
(TargetType="Button").
, (x:Key="buttonStyle").
buttonStyle , Style ( 1.15).

1.15.

<Button Content="" Style="{StaticResource buttonStyle}"/>

1.16.
XAML 379

1.16.

<Page
...
>
<Page.Resources>
<Style TargetType="Button" x:Key="buttonStyle">
<Setter Property="FontSize" Value="48"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Yellow"/>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<Grid x:Name="ContentPanel"
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="" Style="{StaticResource buttonStyle}"/>
</Grid>
</Page>

. -
. , -
buttonStyle ( 1.17).

1.17.

<Style TargetType="Button" x:Key="newButtonStyle"


BasedOn="{StaticResource buttonStyle}">
<Setter Property="Background" Value="Blue"/>
</Style>

BasedOn.
, -
, . -
. -
, .
. -
,
x:Key. 1.18
(. 1.2).

1.18.

<Page
...
>
380 1

<Page.Resources>
<Style TargetType="Button" x:Key="buttonStyle">
<Setter Property="FontSize" Value="48"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Yellow"/>
</Setter.Value>
</Setter>
</Style>

<Style TargetType="Button"
BasedOn="{StaticResource buttonStyle}">
<Setter Property="Background" Value="Blue"/>
</Style>
</Page.Resources>
<Grid x:Name="ContentPanel"
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<StackPanel x:Name="LayoutRoot" Background="Transparent">
<Button Content=" 1"/>
<Button Content=" 2" Style="{x:Null}"/>
<Button Content=" 3"/>
</StackPanel>
</Grid>
</Page>

. 1.2.

,
, -
.
(Style="{x:Null}").
, , -
App.xaml.
( 1.19).

1.19. App.xaml

<Application
x:Class="XAMLApp.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
XAML 381

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:XAMLApp">

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary>
<Style TargetType="Button" x:Key="buttonStyle">
<Setter Property="FontSize" Value="48"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Yellow"/>
</Setter.Value>
</Setter>
</Style>

<Style TargetType="Button"
BasedOn="{StaticResource buttonStyle}">
<Setter Property="Background" Value="Blue"/>
</Style>
</ResourceDictionary>
<ResourceDictionary Source="Common/StandardStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>

</ResourceDictionary>
</Application.Resources>
</Application>

XAML-
. -
. 1.18
, 1.19 . -
, . 1.20
.

1.20.

<Button Content=" 4">


<Button.Resources>
<Style TargetType="Button">
<Setter Property="FontSize" Value="38"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Red"/>
</Setter.Value>
382 1

</Setter>
</Style>
</Button.Resources>
</Button>


App.xaml, .
XAML-, .
Styles.xaml Resource Dictionary
,
( 1.21).

1.21. Styles.xaml

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Style TargetType="Button" x:Key="buttonStyle">
<Setter Property="FontSize" Value="48"/>
<Setter Property="Foreground">
<Setter.Value>
<SolidColorBrush Color="Yellow"/>
</Setter.Value>
</Setter>
</Style>

<Style TargetType="Button"
BasedOn="{StaticResource buttonStyle}">
<Setter Property="Background" Value="Blue"/>
</Style>
</ResourceDictionary>

App.xaml (-
1.22).

1.22.

<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles.xaml"/>
<ResourceDictionary Source="Common/StandardStyles.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
XAML 383

!
,
StandardStyles.xaml, .



, .
.
, , .
.

, ,
, Windows 8. ,
. . XAML -
.

1.23 (. 1.3).

1.23.

<Button Content="" Width="350" Height="100">


<Button.Template>
<ControlTemplate>
<Grid>
<Ellipse Stroke="{StaticResource
ApplicationForegroundThemeBrush}"
StrokeThickness="4" StrokeDashArray="4 2"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"/>
<ContentPresenter VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Button.Template>
</Button>

ContentPresenter.

. 1.3.
384 1

,
, . -
.
1.23
. , .

VSM (Visual State Manager),
9.
, , XAML-
( 1.24), , .

1.24.

<Page
...
>
<Page.Resources>
<ControlTemplate x:Key="buttonTemplate" TargetType="Button">
<Grid>
<Ellipse Stroke="{StaticResource
ApplicationForegroundThemeBrush}"
StrokeThickness="4" StrokeDashArray="4 2"
VerticalAlignment="Stretch"
HorizontalAlignment="Stretch"/>
<ContentPresenter VerticalAlignment="Center"
HorizontalAlignment="Center"/>
</Grid>
</ControlTemplate>
</Page.Resources>
<Grid x:Name="ContentPanel"
Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Button Content="" Width="350" Height="100"
Template="{StaticResource buttonTemplate}"/>
</Grid>
</Page>


,
,
.
:
 Canvas;
 StackPanel;
 Grid.
XAML 385

Canvas .
-
. Canvas -
(Attached Properties),
. Canvas.Top -
Button, -
Canvas.
(Button) Canvas , 1.25.

1.25. Canvas

<Canvas>
<Button Canvas.Top="75" Canvas.Left="75" Content=" T75.L75.Z-1"
Canvas.ZIndex="-1" FontSize="18" Width="200"
Height="75" Background="Orange" />

<Button Canvas.Top="175" Canvas.Left="5" Content=" T175.L45"


FontSize="18" Width="200" Height="75" />

<Button Canvas.Top="110" Canvas.Left="90" Content=" T95.L90"


FontSize="18" Width="220" Height="75" />
</Canvas>

(. 1.4).
,
Canvas.

. 1.4. Canvas
386 1

!
, ZIndex, ,
.

Canvas ,
, , -
-
.
Canvas ,
Grid StackPanel. Canvas -
.
StackPanel , -
-
( ). StackPanel
( 1.26).

1.26. StackPanel

<StackPanel>
<Button Margin="0,0,0,10" Content=" 0.0.0.10"
FontSize="18" Width="200" Height="75" />
<Button Content=" 0.0.0.0" FontSize="18"
Width="200" Height="75" />
<Button Margin="0,50,0,0" Content=" 0.50.0.0"
FontSize="18" Width="200" Height="75" />
<Button Margin="150,170,0,0" Content=" 150.170.0.0"
FontSize="18" Width="200" Height="75" />
</StackPanel>


Visual Studio, . -
Margin, -
.

StackPanel ,
. 1.5.
StackPanel ( 1.27).

1.27. StackPanel

<StackPanel Orientation="Horizontal">
<Button Margin="0,0,0,10" Content=" 0.0.0.10"
FontSize="18" Width="200" Height="75" />
<Button Content=" 0.0.0.0" FontSize="18"
Width="200" Height="75" />
XAML 387

<Button Margin="0,50,0,0" Content=" 0.50.0.0"


FontSize="18" Width="200" Height="75" />
<Button Margin="150,0,0,0" Content=" 150.0.0.0"
FontSize="18" Width="200" Height="75" />
</StackPanel>

, . 1.6.

. 1.5.

StackPanel

. 1.6. StackPanel ( )

Grid -
. Grid
. Grid -
, , ,
.
388 1

1.28.

1.28. Grid

<Grid Width="600" Height="600">


<Grid.RowDefinitions>
<RowDefinition Height="200"/>
<RowDefinition Height="*"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="200" />
</Grid.ColumnDefinitions>

<Button Grid.Column="0" Grid.Row="0" Content=" 0.0"


FontSize="18" Width="140" Height="75" />

<Button Grid.Column="2" Grid.Row="0" Content=" 2.0"


FontSize="18" Width="140" Height="75" />

<Button Grid.Column="1" Grid.Row="2" Content=" 1.2"


FontSize="18" Width="140" Height="75" />
</Grid>

!
, (Grid.Row) (Grid.Column) -
.


:
 ;
 , (Auto);
 (*).
, 200 ,
, , , -
.
. 1.7.
, -
Grid.RowSpan.
Grid.ColumnSpan. -
1.29 , .
XAML 389

. 1.7. Grid

1.29. Grid.RowSpan Grid.ColumnSpan

<Button Content=""
VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
Grid.RowSpan="2" Grid.ColumnSpan="3" />


, -
. -
- . -
, . -
Binding.
, -
, ,
.
.
390 1

-
( 1.30).

1.30.

<StackPanel>
<Slider x:Name="slValue" />
<TextBox Text="{Binding Path=Value, ElementName=slValue}"/>
</StackPanel>

:
="{Binding ___}"

1.30 Text TextBox


Value Slider slValue.
, 1.30,
,
(. 1.8).

. 1.8.


, . ,
.
(Mode=TwoWay) ( 1.31).

1.31.

<StackPanel>
<Slider x:Name="slValue" />
<TextBox
Text="{Binding Path=Value, ElementName=slValue, Mode=TwoWay}" />
</StackPanel>

-
.

Path ( 1.32).
XAML 391

1.32. Path

<StackPanel>
<Slider x:Name="slValue" />
<TextBox Text="{Binding Value, ElementName=slValue, Mode=TwoWay}" />
</StackPanel>

1 100. , ,
1 40 , -
40 80 , 80 100 .
(Background) , -
, . . , -
double. . -
, .
IValueConverter ( 1.33).

1.33.

public class DoubleToBrushConvertor : IValueConverter


{
public object Convert(object value, Type targetType,
object parameter, string language)
{
if (value is double)
{
var doubleVal = (double)value;
if (doubleVal < 40)
{
return new SolidColorBrush(Colors.Green);
}

if (doubleVal < 80)


{
return new SolidColorBrush(Colors.Yellow);
}

return new SolidColorBrush(Colors.Red);


}

return new SolidColorBrush(Colors.Transparent);


}

public object ConvertBack(object value, Type targetType,


object parameter, string language)
{
throw new NotImplementedException();
}
}
392 1

IValueConverter -
: Convert ConvertBack. DoubleToBrushConvertor -
.
XAML--
( 1.34).

1.34.

<Page.Resources>
<local:DoubleToBrushConvertor x:Key="doubleToBrushConvertor"/>
</Page.Resources>

( 1.35).

1.35.

<StackPanel>
<Slider x:Name="slValue" />
<TextBox
Text="{Binding Value, ElementName=slValue, Mode=TwoWay}"

Background="{Binding Value,ElementName=slValue,
Converter={StaticResource doubleToBrushConvertor}}"/>
</StackPanel>

-
.

DataContext
- DataContext,
-
, DataContext. -
- .
, Person ( 1.36), -
(, e-mail).

1.36. Person

public class Person


{
public string LastName { get; set; }
public string FirstName { get; set; }
public string Email { get; set; }
}
XAML 393

( 1.37).

1.37.

<StackPanel x:Name="spPerson">
<TextBox Text="{Binding FirstName}"/>
<TextBox Text="{Binding LastName}"/>
<TextBox Text="{Binding Email}"/>
</StackPanel>

Person
StackPanel spPerson ( 1.38).

1.38. DataContext

Person person=new Person();


person.LastName = "";
person.FirstName = "";
person.Email = "ivan.ivanov@foo.com";

spPerson.DataContext = person;

spPerson
Person.
DataContext . ,
MVVM
(Model View ViewModel).

Person, . -
, Person .
,
INotifyPropertyChanged PropertyChanged -
( 1.39).

1.39. INotifyPropertyChanged

public class Person : INotifyPropertyChanged


{
private string _lastName;
private string _firstName;
private string _email;

public string LastName


{
get { return _lastName; }
394 1

set
{
_lastName = value;
OnPropertyChanged("LastName");
}
}

public string FirstName


{
get { return _firstName; }
set
{
_firstName = value;
OnPropertyChanged("FirstName");
}
}

public string Email


{
get { return _email; }
set
{
_email = value;
OnPropertyChanged("Email");
}
}

public event PropertyChangedEventHandler PropertyChanged;

public void OnPropertyChanged(string propertyName)


{
var evt = PropertyChanged;
if (evt != null)
{
evt(this, new PropertyChangedEventArgs(propertyName));
}
}
}

, Person,
.
1.39 -
. ,
[CallerMemberName],
( ) ( 1.40).
XAML 395

1.40. [CallerMemberName]

public class Person : INotifyPropertyChanged


{
private string _lastName;
private string _firstName;
private string _email;

public string LastName


{
get { return _lastName; }
set { SetProperty(ref _lastName, value); }
}

public string FirstName


{
get { return _firstName; }
set { SetProperty(ref _firstName, value); }
}

public string Email


{
get { return _email; }
set { SetProperty(ref _email, value); }
}

public event PropertyChangedEventHandler PropertyChanged;

protected bool SetProperty<T>(ref T storage, T value,


[CallerMemberName] String propertyName = null)
{
if (object.Equals(storage, value)) return false;

storage = value;
this.OnPropertyChanged(propertyName);
return true;
}

protected void OnPropertyChanged(


[CallerMemberName] string propertyName = null)
{
var eventHandler = this.PropertyChanged;
if (eventHandler != null)
{
eventHandler(this,
new PropertyChangedEventArgs(propertyName));
}
}
}
396 1


Person. -
ObservableCollection<T>, . . , (-
, List<T>), .
ObservableCollection<T>
. -
Person ( 1.41).

1.41.

public sealed partial class MainPage : Page


{
public ObservableCollection<Person> Persons { get; set; }

public MainPage()
{
this.InitializeComponent();

Persons = new ObservableCollection<Person>();


DataContext = this;

Person ivanov = new Person();


ivanov.LastName = "";
ivanov.FirstName = "";
ivanov.Email = "ivan.ivanov@foo.com";
Persons.Add(ivanov);

Person petrov = new Person();


petrov.LastName = "";
petrov.FirstName = "";
petrov.Email = "petr.petrov@foo.com";
Persons.Add(petrov);

Person sidorov = new Person();


sidorov.LastName = "";
sidorov.FirstName = "";
sidorov.Email = "sergey.sidorov@foo.com";
Persons.Add(sidorov);
}

protected override void OnNavigatedTo(NavigationEventArgs e)


{

}
}
XAML 397

( 1.42).

1.42.

<ListBox ItemsSource="{Binding Persons}">

</ListBox>

1.42 (ItemsSource)
ListBox Persons . -
MainPage, ListBox
Persons MainPage.
, ,
Person (. 1.9).

. 1.9. Person

ListBox, -
Person ( 1.43).

1.43. ListBox

<ListBox ItemsSource="{Binding Persons}">


<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Margin="2">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}"/>
<TextBlock Text="{Binding LastName}"
Margin="5,0,0,0"/>
</StackPanel>
<TextBlock Text="{Binding Email}"/>
</StackPanel>
398 1

</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

Person,
.
(. 1.10).

. 1.10. ListBox

XAML. ,
, -
. , -
.
XAML . ,
XAML- C# ( ,
C++ Visual Basic).

XAML-. , -
, XAML-
. , ,
.
poee2

C# 5

C#, ,
. ,
, .
-
, -
. Windows 8 Windows Runtime -
. -
, ,
(. 2.1).

. 2.1.
400 2

.
Microsoft , -
. , , Silverlight WebClient, -
http,
DownloadString, DownloadStringAsync
DownloadStringCompleted -
. , , ?
WebClient "" .
WPF- -
MainWindow.xaml ( 2.1).

2.1. XAML- MainWindow.xaml

<Window x:Class="WpfApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="600" Width="800">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="txtResult"
Grid.Row="0" AcceptsReturn="True" Margin="10"/>
<Button Content=""
Grid.Row="1" Width="250" Margin="10" Click="Button_Click"/>
</Grid>
</Window>


http://akhmed.ru ( 2.2).

2.2. DownloadString

public partial class MainWindow : Window


{
public MainWindow()
{
InitializeComponent();
}

private void Button_Click(object sender, RoutedEventArgs e)


{
var client = new WebClient();
txtResult.Text = client.DownloadString("http://akhmed.ru");
}
}
C# 5 401

? -

. "" , .
? , -
, - ,
, (
).
, "" -
? , , (Thread)
. WebClient
DownloadStringAsync,
( 2.3).

2.3.

public partial class MainWindow : Window


{
public MainWindow()
{
InitializeComponent();
}

//private void Button_Click(object sender, RoutedEventArgs e)


//{
// var client = new WebClient();
// txtResult.Text = client.DownloadString("http://akhmed.ru");
//}

private void Button_Click(object sender, RoutedEventArgs e)


{
var client = new WebClient();
client.DownloadStringCompleted += ClientDownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://akhmed.ru"));
}

void ClientDownloadStringCompleted(object sender,


DownloadStringCompletedEventArgs e)
{
txtResult.Text = e.Result;
}
}

, . -
( 2.4).
402 2

2.4.

private void Button_Click(object sender, RoutedEventArgs e)


{
var client = new WebClient();
client.DownloadStringCompleted += (s, a) =>
{
txtResult.Text = a.Result;
};

client.DownloadStringAsync(new Uri("http://akhmed.ru"));
}

.
, -
. , http://habrahabr.ru, http://yandex.ru http://mail.ru
( 2.5).

2.5.

private void Button_Click(object sender, RoutedEventArgs e)


{
var summ = 0;
var client = new WebClient();

client.DownloadStringCompleted += (s1, a1) =>


{
summ += a1.Result.Length;
var client2 = new WebClient();

client2.DownloadStringCompleted += (s2, a2) =>


{
summ += a2.Result.Length;
var client3 = new WebClient();

client3.DownloadStringCompleted += (s3, a3) =>


{
summ += a3.Result.Length;
txtResult.Text = summ.ToString();
};

client3.DownloadStringAsync(new Uri("http://mail.ru"));
};

client2.DownloadStringAsync(new Uri("http://yandex.ru"));
};
client.DownloadStringAsync(new Uri("http://habrahabr.ru"));
}
C# 5 403

. - -
,
if,
try/catch.

, ,
. , . -
,
( 2.6).

2.6. 2.5

private void Button_Click(object sender, RoutedEventArgs e)


{
var summ = 0;
summ += GetLength("http://habr.ru");
summ += GetLength("http://yandex.ru");
summ += GetLength("http://mail.ru");
txtResult.Text = summ.ToString();
}

private int GetLength(string url)


{
return new WebClient().DownloadString(new Uri(url)).Length;
}

GetLength ,
. , -
try/catch.

async await
C# 5
async await C# 5
.
, WPF-
, .NET
Framework 4.5 ( 2.7).


Async Targeting Pack for Visual Studio 2012 -
async await Silverlight 5
.NET Framework 4.0.
404 2

2.7. WPF

private async void Button_Click(object sender, RoutedEventArgs e)


{
var client = new WebClient();
var uri = new Uri("http://akhmed.ru");
txtResult.Text = await client.DownloadStringTaskAsync(uri);
}

2.7 2.4 .
. , ,
: async await .

DownloadStringTaskAsync, Task<string>. -
(
await), .
async await Windows Store-
. Windows Store- , -
WPF .
, .
Windows 8
, .
, -
. , http Windows Store-
( 2.8).

2.8. habr.ru WinRT

public sealed partial class MainPage : Page


{
public MainPage()
{
this.InitializeComponent();
}

private async void Button_Click(object sender, RoutedEventArgs e)


{
var client = new HttpClient();
txtResult.Text = await client.GetStringAsync("http://habr.ru");
}
}

, ? -
, async await.
C# 5 405

, async await,
Task Task<T>, .
GetStryngAsync Task<string>,
, string.
, -
Wait ( 2.9).

2.9.

private void Button_Click(object sender, RoutedEventArgs e)


{
var client = new HttpClient();
var task = client.GetStringAsync("http://habr.ru");
task.Wait();
txtResult.Text = task.Result;
}

, ,
"" , . -
await ( 2.8),
. Button_Click ,
. Button_Click,
await, .
.
.
async await, (-
2.10).

2.10.

private async void Button_Click(object sender, RoutedEventArgs e)


{
var contentHabrahabr = await new
HttpClient().GetStringAsync("http://habrahabr.ru");
var contentYandex = await new
HttpClient().GetStringAsync("http://yandex.ru");
var contentMail = await new
HttpClient().GetStringAsync("http://mail.ru");

var length = contentHabrahabr.Length + contentYandex.Length


+ contentMail.Length;

txtResult.Text = length.ToString();
}
406 2

, .
, .
Task -
. , -
, , . Task
WhenAll, -
( 2.11).

2.11.

private async void Button_Click(object sender, RoutedEventArgs e)


{
var taskHabrahabr =
new HttpClient().GetStringAsync("http://habrahabr.ru");
var taskYandex = new HttpClient().GetStringAsync("http://yandex.ru");
var taskMail = new HttpClient().GetStringAsync("http://mail.ru");
await Task.WhenAll(taskHabrahabr, taskYandex, taskMail);

var length = taskHabrahabr.Result.Length


+ taskYandex.Result.Length
+ taskMail.Result.Length;

txtResult.Text = length.ToString();
}

. -
, . .
,
,
Task.Factory ( 2.12) ,
await.

2.12.

var txt = await Task<string>.Factory.StartNew(() =>


{
//
return "Hello World";
});

, -
. -
. ( ) Windows Store-
.
C# 5 407

async await C# 5 -
. Task
Task<T>. Windows 8 , -
( 50 ), ,
,
.
, . -
, , -
. , async await -
. .
, , ,
.

A DeviceInformation 256
DLL- 142
Accelerometer 279
DreamSpark 355
Animation Library 316
Application Bar 12, 18, 77
ApplicationLanguages 291 F
Assemblies 39
async 45, 403 FileIO 219
Attached Properties 385 FileOpenPicker 229
await 45, 403 FileSavePicker 232
Filled 17, 125
B Flyout 84
FolderPicker 233
BackgroundTaskBuilder 147 Frame 59
Badge 156 Frameworks 39
BadgeUpdateManager 173 Full Screen 16, 125
Bauhaus 303
"Best at statement" 324
Binding 389
G
Blend for Visual Studio 27 Geolocator 262
Global Position System, GPS 259
C Grid 387
Gyrometer 282
CachedFileManager 233
CameraCaptureUI 245
Canvas 385 I
Charms 19, 347 i18n 289
Chrome 307
In-App Purchases 355
Clipboard 198
Inclinometer 285
Compass 286
Culture 290 Information Architecture 304
CultureInfo 290 International Typographic Style 23, 303
CurrentApp 366 Internationalization 289
CurrentAppSimulator 366 ItemTemplate 102

D J
DataTransferManager 196 JSON 205
Dependency Property 94 JsonObject 205
410

L Share 194
Sharing 318
Language Integrated Quiries, LINQ 224 SimpleOrientationSensor 287
LayoutAwarePage 94, 130 Snapped 16, 125
LicenseInformation 366 Snapped Mode 338
LightSensor 276 Socket API 89
Live ID 358 SQLite 221
Live Tile 162 SQL- 227
Lock Screen 143 StackPanel 386
Storyboard 132
M Suggestions 180
Swiss Design 303
MediaCapture 256 SyndicationClient 89
Microsoft Advertising 355
Motion Design 23, 303 T
MVVM 393
Task 405
O Task<T> 405
Tile 19, 156
Object-Relational Mapping, ORM 224 TileUpdateManager 168
TileUpdater 166
Toast 156
P Toast Notification 151
Pivots 338 Trial 355
Pixels Per Inch, PPI 133
Popup 84, 213 U
PopupMenu 85
Push Notification 155 User Account Control, UAC 181
Push- 151
V
R Visual State Manager, VSM 28, 132
RandomAccessStreamReference 202 Visual Studio 26
Raw 156
Remote Desktop 46 W
Resource leak 278
Windows App Certification Kit, WACK 364
S Windows Push Notification Services, WNS
142, 156
SampleDataSource 88 Windows Runtime 15, 21
Sandbox 216 WinRT 21
SearchPane 187 WnsRecipe 161
Secondary Tiles 20, 162, 177 WYSIWYG 40
Security Code 359
Semantic Zoom 115, 312, 334 X
Sensor Fusion 283
Settings 209 XAML-
SettingsCommand 211 41
SettingsPane 209 SecondPage.xaml 56
411

344
307
60 115, 312,
315 334
163 307, 344
181
348
347
290
Bing Maps SDK 267 291
NotificationsExtensions 168
SQLite for Windows Runtime 222
sqlite-net 224
31
WnsRecipe 161
289
316
360

356
384
309 Canvas 385
Grid 387
StackPanel 386

173, 174 85, 345
290 347
103 256


- 366 308, 332
333
24 334
25
301
303
"" 313
307
318
338 83, 213
316, 338

173
304, 329 "" 216
338
316, 338
177
256 166, 175
293 170
412

19


188
191 151
348 155
374 158
375 359
Windows Store 32



181

Filled 17 App.xaml 36, 380
Full Screen 16 App.xaml.cs 37, 137, 182, 236
Snapped 16 LicenceInfo.xml 367
121 MainPage.xaml 35
115 MainPage.xaml.cs 35, 41
115 Package.appxmanifest 37, 182, 199, 291
162 SampleDataSource.cs 88
16, 125 StandardStyles.xaml 37, 81
Vsix 267
249
WindowsStoreProxy.xml 366
142
382 229
294
232
310
325
389
WNS 156 251
304
250
344
137
FutureAccessList.Add 239
378
GetDefault() 279
379
PostToWns 159
58
405
72
325

"-" 19

- 15


71
28, 70 Basic Page 56, 62
24 Grid App 70, 87
198 152
163
144 114
145 383
413

(.)
32
163
102 SQL 221
384 292
305 301
315

143
321

Вам также может понравиться