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

Windows 8, .



. Microsoft
Most Valuable Professional (MVP) Microsoft Silverlight.
Digital Cloud
Technologies. ,
XAML/C#-. Microsoft
(MCT) Imagine Cup.
.Net
Silverlight .

12 . Microsoft 2002 .
,
.NET. http://baydachnyy.com.

1.

........................ 9

Windows 8 ..............................................................................10
Windows Runtime (WinRT) ........................................................................................16
...................................................................................21
C# .....................................................................................30
.....................................................................................34

2.

................................... 37

XAML ..........................................................................................................38
Metro .............................................................52
..............................................................................................60
.............................................................................67
Application Bar ...............................................................................................................84
.......................................................................88
........................................................................................................................93

3.

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

..................................................................................................................................98
.......................................................................................................................... 103
................................................................................... 106

4.

, ........................... 109

....................................................................................... 110
............................................................................................................................... 116
.................................................. 118
......................................................................................................... 120
............................................................................................ 126
............................................................................................ 131
5

Windows 8 C#

5.

.............................................................. 139

................................................. 140
................................................................................................. 143
............................................................................................ 149
................................................................................................. 153
MVVM ....................................................................... 156

6.

Metro . 163

....................................................................................................... 164
............................................. 172
Push ........................................................................... 177
......................................................................................... 180

7.

. .................................................................... 187

.................................................................... 188
.......................................................... 189
................................................................................ 191
RSS .............................................................................................. 194
WebAuthenticationBroker .................................................................... 196
....................................... 198

8.

........... 199

....................................................................................................................... 200
Expression Blend ................................................................................. 206

9.

..................................................... 213

MediaElement ..................................................................................... 214


MediaPlayer ......................................................................................... 225
.............................................................................. 226
......................................................................................... 231
PlayTo ............................................................................................ 232

10.

... 235

.......................................................................... 236
..................................................................................................... 241
........................................................................... 243

11.

........................ 247

...................................................................... 248
Windows Store .............................................................................. 256

12.

,
................................. 267

.......................................................................................................................... 268
.............................................................................................................. 271
........................................ 274

1.

Windows 8 C#

Windows 8
Windows 8
,
.
, Windows ,
Windows 8.
, Windows, .NET-,
, Windows Presentation Foundation, ASP.NET, Silverlight
. ,
. ,
ASP.NET,
Windows Form,
Windows Presentation Foundation,
Silverlight.
.NET Framework,

. ,
,
. ,
C++ C# VB.NET.
, Windows- ,
.NET Framework
, C#.
, .NET Framework

(Win API), ,
- .
, ,
,
.
. , Nokia,
Windows Phone, 1,4 ,
, ,
.
.
, .

.
10

1.
, ,
(
),
Windows Presentation Foundation. WPF DirectX
,
. Windows Presentation Foundation
API, , DirectX
.
, Windows-,
.
, .
.
,
:
( ,
).
, ARM ,
, Windows- -
Windows (x86, x64).

Windows, - . ,
Windows
MS-DOS.
, , ,
, .


Windows 8 ,
, .
Windows 8 ,
,
, ARM-. ,
Windows 8 Windows 7,
,
.

( ), .
, Metro,
11

Windows 8 C#
Windows Phone
, Microsoft.

Windows 8.
, ,
.
,
, . , Windows 8,
(tiles)
.
, .

. 1.1.
,
, (
,
, ).
Windows Phone,
. ,
, , ,
, .

12

1.

. ,
Windows 8
, .
Metro .
, ,
. ,
( ,
, ),
.
XAML,
WPF Silverlight. ,
.
,
. Windows 8
(Application Bar) . ,
( ),

Win+C ( ).

.

. 1.2.

13

Windows 8 C#
:

Windows 8, ,
. , Settings
, Search
.

.
,
,
.
,

.
( ) 1366 .

. 1.3.

. 1.4.
, , ,
.
14

1.


,
Metro, ,
Windows 8 .
API, . API
, : ,
,
. , API
-.
, ,
, , API Silverlight
Windows Presentation Foundation. ,
.NET-, API Windows 8 .
Microsoft , Windows 8
. ,
C# VB.NET, C++
JavaScript. C++ C#,
XAML, JavaScript, HTML 5.
,
C#/XAML. HTML 5/
JavaScript, .


, ,
. :
Windows Phone, Windows 8, API,
Windows (Marketplace),
.
,
. Windows,
,
.
Windows 8,
Metro,
.
Windows Runtime, WinRT.

15

Windows 8 C#

Windows Runtime (WinRT)


, Windows Runtime
Metro.
, -
.
User Interface

HTML5/CSS

XAML

DirectX

Controls

Data Binding

SVG

Tiles

Input

Accessibility

Printing

Devices

Geolocation

Portable

Communications & Data

Sensors

NFC

Contracts

Media

Playback

Capture

Local & Cloud Storage

Web

Streams

SMS

Notifications

PlayTo

Visual
Effects

Background Transfer

XML

Networking

Cryptography

Globalization

Fundamentals
Application
Services

Threading/Timers

Memory
Management

Authentication

. 1.5.
, Windows Runtime .
,
, .
.

.
,
,
.
,
,
, .
,
.
16

1.
,
, .


.
, Windows Runtime
. ,
Windows 8,
:
, -
(
); ,
,
;
.
, WinRT ,
, WinRT.
WinRT,
, :
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsRuntime\ActivatableClassId

. 1.6.
,
, System32.
, WinRT
.
: .NET Framework C# ?
17

Windows 8 C#
, , C#
( -) ,
DllImport. ,
C#, .
, .
COM- Visual Studio
-, COM
. ,
.NET Framework,
(, IntelliSense .).
Windows Runtime, ,
Win 32 API COM, .NET
Framework C#. WinRT,
.NET Framework. .
, WinRT ,
C++, C#. ,
C#-, WinRT
.NET Framework , .
# ,
.NET Framework. - Windows 8?
C#, ,
,
.NET Framework, Windows
Runtime. , .NET Framework,
. Windows 8 Metro
,
.
LINQ Metro
C#. .NET-
Metro .
Windows Runtime
, , .NET Framework WinRT,
?
Language Projection.
WinRT C#. , Language Projection
-, ,
C# .
. , , JavaScript/HTML
5, , WinJS,
WinRT JavaScript.
, , Metro,
C#, .
18

1.
Metro (C#/XAML)
Language Projection

Common Language Runtime (CLR)


Windows Runtime

. 1.7.
, ,
. , .NET Framework
,
, .
,
, IntelliSense. ,
, Windows
. ,
WinRT , ,
.NET Framework ( ,
.NET). , WInRT
,
C:\Windows\System32\WinMetadata.
.winmd, WinRT.

. 1.8.

19

Windows 8 C#
,
ildasm, (
: C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools).

. 1.9.

20

1.


Windows Runtime, C# .NET Framework
Metro, .
, , Visual Studio.
Microsoft ,
Express, Visual Studio.
Express.
Windows 8
http://msdn.microsoft.com/en-us/windows/apps/.
Visual Studio, .
, .

. 1.10.
, Visual Studio
Metro: VB.NET/XAML, C#/XAML, C++/XAML, JavaScript/HTML 5.
++
,
DirectX.
, ++.

21

Windows 8 C#
JavaScript HTML 5 ,
-.
Windows 8 ( WinJS),
JQuery, HTML 5. HTML 5 JavaScript
, , Facebook (
, -
).
, VB.NET C#
.NET Framework. C#,

. C# , ,
, .
, ,
HTML 5 JavaScript. , C#
, , DirectX.
Windows 8.
,
C#.
Blank Application. . ,
, .
,
.
Grid Application. ,
, ,
. , ,
.

, .
Split Application.
,
.
,
.
. , ,

, .

22

1.

. 1.11.

. 1.12.
23

Windows 8 C#

. 1.13.
,
Metro. .
.
Class Library.
WinRT ( ,
.Net- ,
);
Unit Test Library.
Unit-.
24

1.
, Visual Studio InteliSense.
,
Windows Runtime. XAML
, . Visual
Studio .
.
. ,
Metro . ,
-,
. Visual Studio
Package.appxmanifest XML-.
.
<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/2010/manifest">
<Identity Name="519f4c47-a156-4f8e-b96b-d408a0aba6dd"
Publisher="CN=Sergiy"
Version="1.0.0.0" />
<Prerequisites>
<OSMinVersion>6.2</OSMinVersion>
<OSMaxVersionTested>6.2</OSMaxVersionTested>
</Prerequisites>
<Resources>
<Resource Language="x-generate"/>
</Resources>
<Properties>
<DisplayName>Application2</DisplayName>
<PublisherDisplayName>Sergiy</PublisherDisplayName>
<Logo>Assets\StoreLogo.png</Logo>
<Description>Application2</Description>
</Properties>
<Applications>
<Application Id="App"
Executable="$targetnametoken$.exe"
EntryPoint="Application2.App">
<VisualElements
DisplayName="Application2"
Logo="Assets\Logo.png"
SmallLogo="Assets\SmallLogo.png"
25

Windows 8 C#
Description="Application2"
ForegroundText="light"
BackgroundColor="#222222">
<DefaultTile ShowName="allLogos" />
<SplashScreen Image="Assets\SplashScreen.png" />
</VisualElements>
</Application>
</Applications>
<Capabilities>
<Capability Name="internetClient" />
</Capabilities>
</Package>
, ,
, ,
.
,
.
Visual Studio .
.appxmanifest .

. 1.14.
26

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

. 1.15.
. ,
Metro Windows 8 .
,
. ,
. , ,
. Windows 8
,
.

27

Windows 8 C#

( ).

. ,
,
Search .
,
.
, .

. 1.16.
, ,
Windows.

28

1.

. 1.17.

,
, ().

. ,
Launch, .
, HKEY_CURRENT_USER\Software\Classes\
Extensions\ContractId\Windows.Launch.

. 1.18.

29

Windows 8 C#

C#
Metro
C#.
BlankPage.xaml.
Grid, Page.
Grid VerticalAlignment="Center",
TextBox, :

<TextBlock Text="Hello Windows 8!" TextAlignment="Center"


FontSize="64" Name="fillBox" />
, , "Hello
Windows 8!".
.
, .

. 1.19.
, ,

.
Page ,
: Loaded="Page_Loaded", Unloaded="Page_
Unloaded". .
30

1.
private void Page_Loaded(object sender, RoutedEventArgs e)
{
ApplicationView.GetForCurrentView().ViewStateChanged +=
this.ViewStateChanged;
VisualStateManager.GoToState(this,
ApplicationView.Value.ToString(), false);
}
private void Page_Unloaded(object sender, RoutedEventArgs e)
{
ApplicationView.GetForCurrentView().ViewStateChanged -=
this.ViewStateChanged;
}
, Page_Loaded, ,
ViewStateChanged ApplicationView,
( ),
ViewStateChanged
. Page_Loaded
. GoToState
VisualStateManager,
Silverlight WPF.
ViewStateChanged :
private void ViewStateChanged(ApplicationView sender,
ApplicationViewStateChangedEventArgs e)
{
VisualStateManager.GoToState(this, e.ViewState.ToString(), false);
}

VisualStateManager .

, .
ApplicationViewState.
Filled Metro
. (Snapped)
,
Filled.
FullScreenLandscape .
FullScreenPortrait .
Snapped .
31

Windows 8 C#
,
,
.
XAML-.
Grid :
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="OrientationStates">
<VisualState x:Name="FullScreenLandscape" />
<VisualState x:Name="Filled" />
<VisualState x:Name="FullScreenPortrait" />
<VisualState x:Name="Snapped">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetProperty="Visibility"
Storyboard.TargetName="snappedPanel">
<DiscreteObjectKeyFrame KeyTime="0" Value="Visible">
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetProperty="Visibility"
Storyboard.TargetName="fillBox">
<DiscreteObjectKeyFrame KeyTime="0" Value="Collapsed">
</DiscreteObjectKeyFrame>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<TextBlock Text="Hello Windows 8!" TextAlignment="Center"
FontSize="64" Name="fillBox" />
<StackPanel HorizontalAlignment="Center"
VerticalAlignment="Center" Name="snappedPanel" Visibility="Collapsed">
<TextBlock Text="H" FontSize="64" HorizontalAlignment="Center" />
<TextBlock Text="E" FontSize="64" HorizontalAlignment="Center" />
<TextBlock Text="L" FontSize="64" HorizontalAlignment="Center" />
<TextBlock Text="L" FontSize="64" HorizontalAlignment="Center" />
<TextBlock Text="O" FontSize="64" HorizontalAlignment="Center" />
</StackPanel>

32

1.
StackPanel,
, Hello
. ,
,
, "Hello Windows 8!", ,
. Visibility
VisualStateManager,
.
,
.

. 1.20.
.
,
, LayoutAwarePage.cs.
, , . ,
LayoutAwarePage.cs
,
. LayoutAwarePage ,
, - .
, Blank.

33

Windows 8 C#


Windows 8
,
. ,
,
, .

,
.
, ,
Windows 8
.
Metro Windows 8 Simulator.
Windows 8 Simulator , :

;
;
;
;
GPS-.
( Windows
Phone). , .
Windows 8 Simulator Windows
8, ,
, .
,
Windows 8. Windows
8 Simulator Windows Phone,
(
).
:
( Debug)
,
Start Debugging. .

34

1.

. 1.21.
Simulator Visual Studio ,
Local Computer,
Simulator.

35

Windows 8 C#

. 1.22.
Windows Runtime, Visual
Studio ,
Windows 8.

36

2.

Windows 8 C#

XAML
, C# ++ Windows 8
, XAML,
, .
XAML (eXtensible Application Markup Language)
, XML.
. XAML
, Windows Presentation Foundation
Silverlight. XAML Workflow Foundation
.
XAML, ,
C# Windows Forms.
, , ,
:
this.myButton = new System.Windows.Forms.Button();
this.myButton.Location = new System.Drawing.Point(120, 60);
this.myButton.Name = "myButton";
this.myButton.Size = new System.Drawing.Size(110, 40);
this.myButton.Text = "Hello";
this.Controls.Add(this.myButton);
, , ,
, .
. ,
WinForms, ,
, , . -,
, -,
. ,
, C#, . ,
, .
XAML:
<Canvas x:Name="LayoutRoot">
<Button Content="Hello" Canvas.Top="60" Canvas.Left="120"
Width="110" Height="40" x:Name="myButton"></Button>
</Canvas>
38

2.
, XAML , C#,
, , .
XAML
, .
XAML
,
.
XAML , ,
. ,
, .
.
XAML.


XML, XAML .
XML, ,
.
,
:

<Canvas Name="LayoutRoot">
<Button Content="Hello" Canvas.Top="60" Canvas.Left="120"
Width="110" Height="40" Name="button1"></Button>
</Canvas>
Canvas
(Button). Button
. XML, Button
( ):

<Button Content="Hello" Canvas.Top="60" Canvas.Left="120"


Width="110" Height="40" Name="button1" />
XAML ( XML) .
,
. , Button1 button1:

39

Windows 8 C#
<Button Content="Hello" Canvas.Top="60" Canvas.Left="120"
Width="110" Height="40" Name="button1" />
<Button Content="Hello" Canvas.Top="160" Canvas.Left="120"
Width="110" Height="40" Name="Button1" />
XAML . XML, XAML
, , .
, :
1
<Button Content="Hello" Canvas.Top="60" Canvas.Left="120"
Width="110" Height="40" Name="button1"></Button>
2
<Button Content="Hello" Canvas.Top="60" Canvas.Left="120"
Name="button1">
<Button.Width>
110
</Button.Width>
<Button.Height>
40
</Button.Height>
</Button>
,
. :
1
<Rectangle Width="100" Height="50" Fill="Red"></Rectangle>
2
<Rectangle Width="100" Height="50">
<Rectangle.Fill>
<SolidColorBrush Color="Red" />
</Rectangle.Fill>
</Rectangle>

40

2.
, , ,
Fill SolidColorBrush.
, Color,
.

. ,
Width . Width ,
.
, .
Blank Metro,
, :

public sealed class BooleanToVisibilityConverter : IValueConverter


{
public object Convert(object value, Type targetType,
object parameter, string language)
{
return (value is bool && (bool)value) ?
Visibility.Visible : Visibility.Collapsed;
}
public object ConvertBack(object value, Type targetType,
object parameter, string language)
{
return value is Visibility && (Visibility)value ==
Visibility.Visible;
}
}
,
Visibility.
Visibility: Collapsed
Visible.
bool.
. , .

41

Windows 8 C#
:
1
<TextBlock>
Hello
</TextBlock>
2
<TextBlock Text="Hello"></TextBlock>
, Text TextBlock .
(, , HTML)
XAML. , ,
( ),
ContentPropertyAttribute .
, ,
. :

<Rectangle Width="100" Height="50">


<Rectangle.Fill>
<LinearGradientBrush>
<LinearGradientBrush.GradientStops>
<GradientStopCollection>
<GradientStop Offset="0.0" Color="Red" />
<GradientStop Offset="1.0" Color="Green" />
</GradientStopCollection>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
. ,
, .
,
. , .
, , , GradientStops
, , .
LinearGradientBrush GradientStops:
42

2.
<Rectangle Width="100" Height="50">
<Rectangle.Fill>
<LinearGradientBrush>
<GradientStopCollection>
<GradientStop Offset="0.0" Color="Red" />
<GradientStop Offset="1.0" Color="Green" />
</GradientStopCollection>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
, XAML ,
GradientStops .
. ,
:

<Rectangle Width="100" Height="50">


<Rectangle.Fill>
<LinearGradientBrush>
<GradientStop Offset="0.0" Color="Red" />
<GradientStop Offset="1.0" Color="Green" />
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
, ,
-. , ,
,
, ,
( , Fill).
, , . ,
, ,
. ,
XAML Add .

. , ,
UIElementCollection :

43

Windows 8 C#
<StackPanel x:Name="LayoutRoot" Background="White">
<StackPanel.Children>
<UIElementCollection>
<Button Width="100" Height="50"></Button>
</UIElementCollection>
</StackPanel.Children>
</StackPanel>
:
1
<StackPanel x:Name="LayoutRoot" Background="White">
<StackPanel.Children>
<Button Width="100" Height="50"></Button>
</StackPanel.Children>
</StackPanel>
2 (Children )
<StackPanel x:Name="LayoutRoot" Background="White">
<Button Width="100" Height="50"></Button>
</StackPanel>

XAML
Windows Runtime .NET Framework,
.
. , Button Windows Runtime
Windows.UI.Xaml.Controls. ,
Button Windows.UI.Xaml.Controls.
Button, .
using.
XML, C#, . ,
XML URI , ,
,
, .
,
xmlns. ,
.
, , .
44

2.

, :
xmlns:x="http://baydachnyy.com/schemas"
Metro:

<Page
x:Class="Application3.BlankPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Application3">
.
,
( Application3),
Silverlight WPF.
http://schemas.microsoft.com/winfx/2006/xaml/
presentation ,
. , C#
,
XAML. XAML .
.
, .
http://schemas.microsoft.com/winfx/2006/xaml
. .
x, .
, .
, ( )
XAML, .
xmlns, URI .
Application3.

45

Windows 8 C#


, XAML,
, XAML C#.
, ,
BlankPage.xaml:

<Page
x:Class="HelloWin8App.BlankPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:HelloWin8App"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Loaded="Page_Loaded"
Unloaded="Page_Unloaded">
Visual Studio : BlankPage.xaml BlankPage.cs.
BlankPage.cs ,
C#, ( ).
, BlankPage.cs XAML
Class.
myButton:

<Button Name="myButton" Width="100" Height="50">Hello</Button>


MainPage.cs. MainPage
:

public sealed partial class BlankPage : Page


{
public BlankPage()
{
InitializeComponent();
}
}

46

2.
.
, IntelliSense . ,
Button C# . InitializeComponent
.
Silverlight, :
, Visual Studio.
, InitializeComponent
Go To Definition.
, BlankPage.g.i.cs:

public partial class BlankPage : Windows.UI.Xaml.Controls.Page


{
private Windows.UI.Xaml.Controls.Button myButton;
private bool _contentLoaded;
[System.CodeDom.Compiler.GeneratedCodeAttribute(
"Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent()
{
if (_contentLoaded)
return;
_contentLoaded = true;
Application.LoadComponent(this,
new System.Uri("ms-appx:///BlankPage.xaml"),
Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application);

myButton =
(Windows.UI.Xaml.Controls.Button)this.FindName("myButton");
}
}
, XAML
, InitializeComponent XAML
LoadComponent. XAML ,
ms-appx .
(LoadComponent
this
) ,
, XAML :
47

Windows 8 C#
myButton =
(Windows.UI.Xaml.Controls.Button)this.FindName("myButton");
, BlankPage.g.i.cs BlankPage.cs,
XAML Visual Studio .
XAML, ,
Class Visual Studio,
.
, IntelliSense,
, .
. :
, -
:

Loaded="Page_Loaded"
Unloaded="Page_Unloaded">
Visual Studio,

:

. 2.1.

48

2.
,
:

. 2.2.
, ,

.


,
. ,

,
.
;
.
49

Windows 8 C#
XAML :
Binding
, .
;
StaticResources ;
TemplateBinding Binding,
;
RelativeSource
.
, .
1
<Page.Resources>
<Style x:Name="btnStyle" TargetType="Button">
<Setter Property="Background" Value="Green"></Setter>
</Style>
</Page.Resources>
<Grid x:Name="LayoutRoot" Background="White">
<Button Name="myButton" Width="100" Height="50"
Style="{StaticResource btnStyle}" Content="Hello">
</Button>
</Grid>
,
.
2
<StackPanel x:Name="LayoutRoot" >
<Slider Name="sld1" Width="300" Height="50"
Minimum="100" Maximum="200"
Value="10">
</Slider>
<TextBox Text="Hello" Width=
"{Binding Value, ElementName=sld1, Mode=TwoWay}">
</TextBox>
</StackPanel>

50

2.
Width TextBox
.
.
, Binding
.


- Canvas:

<Canvas>
<Button Content="Hello" Canvas.Top="60" Canvas.Left="120"
Width="110" Height="40" Name="button1" />
</Canvas>
,
, Canvas.Top, Canvas.Left.
.
, XAML ,

( ,
..). , Button
.
,
.
Windows Runtime DependencyObject.
Object ,
. DependencyObject
.
SetValue GetValue,
, .
, Canvas.Top="60",
:

button1.SetValue(Canvas.TopProperty, 60)
, Canvas, ,
GetValue .

51

Windows 8 C#

Metro
,
Metro. ,
.
Metro
. ,
Metro .


,
, , ..
.
, , ,
.
Metro ,
.
,
, .
(Application
Bar),
, .
Internet Explorer 10
Metro. ,

, , .
.

52

2.

. 2.3.
, ,
,
. ,
Internet Explorer 10 ( Metro)
.

. 2.4.
53

Windows 8 C#
,
, -,
.


, Metro,
.
,
(). ,
, .
,
( , ).

.
-
( , . .).

. ,
, .
Windows 8 , ,
.
, .

,
,
:
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="OrientationStates">
<VisualState x:Name="FullScreenLandscape" />
<VisualState x:Name="Filled" />
<VisualState x:Name="FullScreenPortrait" />
<VisualState x:Name="Snapped">
. . . . .
</ VisualState x:Name="Snapped">
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>

54

2.
, , ,
.
,

. ,
.
1024 768,
1366 768 ( ).
.
,
, ,
, .


Windows 8 beta
, ,
.
,
. ,
. , ,
.
,
. ,
, .
, Metro,
:

.
;

, ,
.
:

55

Windows 8 C#



Filled.
,
(Application Bar),
,


,
,
, ..
,

,
( )
.


56

2.
, :



. ,
, -

.

, ,

,


,
,

()



.

,
.

,
, .

57

Windows 8 C#

, ,
. ,
Facebook, Twitter
. ,
Facebook, Twitter .., , ,
.
, , ,
.
,

.
, ,
, ,
. , Windows 8
. :
Search
.
,
;
Sharing
.
;
Play To
;
Settings
,
;
App to App
,
, .
,
,
Declarations. Visual Studio ,
:

58

2.

. 2.5.
6 , Windows 8.

(Tiles)

,
.

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

. ,
,
.

59

Windows 8 C#


WiFi,
3G- . ,

. ,
.
,
,
.


.
Metro
,
. Windows 8 ,

.
, XAML , ,
Metro.
,
.


,
,
. , ,
Page. Page,
XAML ,
UserControl, Content.
UIElement, ,
UserControl.
, Content
. ,
Page, ,

( ).
60

2.
, , ,
.
, , , .
, , ,
,
. .
() ,
Windows.UI.Xaml.Controls
Panel.
Children, UIElement.

Canvas
Canvas.
,
.
. , Windows Forms,
,
Metro
, Metro

.
, .
, , Canvas
.
Canvas:

<Canvas Background="{StaticResource ApplicationPageBackgroundBrush}">


<Button Content="Hello" Canvas.Top="100" Canvas.Left="100"></Button>
</Canvas>
,
(100,100). ,
Top Left.
, Canvas,
Width Height,
.

61

Windows 8 C#

StackPanel
StackPanel.
.
, StackPanel:

<StackPanel x:Name="LayoutRoot">
<Button Content="Button 1"></Button>
<Button Content="Button 2"></Button>
<Button Content="Button 3"></Button>
<Button Content="Button 4"></Button>
</StackPanel>
, StackPanel .
Silverlight ,
StackPanel. Windows Runtime .
, .
StackPanel,
HorizontalAligment Stretch:

<StackPanel x:Name="LayoutRoot"
Background="{StaticResource ApplicationPageBackgroundBrush}">
<Button Content="Button 1" HorizontalAlignment="Stretch"></Button>
<Button Content="Button 2" HorizontalAlignment="Stretch"></Button>
<Button Content="Button 3" HorizontalAlignment="Stretch"></Button>
<Button Content="Button 4" HorizontalAlignment="Stretch"></Button>
</StackPanel>
,
StackPanel Orientation:

<StackPanel x:Name="LayoutRoot" Background="White"


Orientation="Horizontal">
<Button Content="Button 1"></Button>
<Button Content="Button 2"></Button>
<Button Content="Button 3"></Button>
<Button Content="Button 4"></Button>
</StackPanel>

62

2.
, StackPanel
. ,

StackPanel .
:
HorizontalAlignment
,
. : Left, Right,
Center Stretch ( );
VerticalAlignment
, .
: Top, Bottom, Center
Stretch ( );
Margin
. ,
;
MinWidth ();
MinHeight ();
MaxWidth ();
MaxHeight ();
Padding ,
.
StackPanel.

Grid
Grid
.
, .

.
Grid. ShowGridLines,
:

63

Windows 8 C#
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Content="Button 1" Grid.Row="0" Grid.Column="0"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Button>
<Button Content="Button 2" Grid.Row="0" Grid.Column="1"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Button>
<Button Content="Button 3" Grid.Row="1" Grid.Column="2"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"></Button>
</Grid>
Grid:

. 2.6.
, Grid , ,
.
, ,
StackPanel. ,
:
64

2.
,
,
Silverlight;

Auto,
, .
:
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Content="Button 1" Grid.Row="0" Grid.Column="0"></Button>
<Button Content="Button 2" Grid.Row="0" Grid.Column="1"></Button>
<Button Content="Button 3" Grid.Row="1" Grid.Column="2"></Button>
</Grid>

,
. ,
1 2, 1
2 :
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="2*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
<ColumnDefinition Width="2*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button Content="Button 1" Grid.Row="0" Grid.Column="0"></Button>
<Button Content="Button 2" Grid.Row="0" Grid.Column="1"></Button>
<Button Content="Button 3" Grid.Row="1" Grid.Column="2"></Button>
</Grid>
65

Windows 8 C#
Grid
. :
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"></ColumnDefinition>
<ColumnDefinition Width="Auto"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="Employee" Grid.Row="0" Grid.Column="0"
Grid.ColumnSpan="2" HorizontalAlignment="Center"
FontSize="16" FontWeight="Bold" Margin="5">
</TextBlock>
<TextBlock Text="First Name:" Grid.Row="1"
Grid.Column="0" Margin="5"></TextBlock>
<TextBox Grid.Column="1" Grid.Row="1" MinWidth="100"
Margin="5"></TextBox>
<TextBlock Text="Last Name:" Grid.Row="2" Grid.Column="0"
Margin="5"></TextBlock>
<TextBox Grid.Column="1" Grid.Row="2" MinWidth="100"
Margin="5"></TextBox>
<TextBlock Text="EMail:" Grid.Row="3" Grid.Column="0"
Margin="5"></TextBlock>
<TextBox Grid.Column="1" Grid.Row="3" MinWidth="100"
Margin="5"></TextBox>
<Button Grid.Column="0" Grid.Row="4" Grid.ColumnSpan="2"
Content="Send" Margin="5"
HorizontalAlignment="Center" Padding="5">
</Button>
</Grid>

66

2.

WrapGrid
, , WrapGrid.
,
, .
,
, . . ,
.
Silverlight, WindowsRuntime WrapGrid
, ItemsControl (ListView,
GridView ..). .


,
, .

Control
, ,
Windows.UI.Xaml.Controls.Control,
, .
, :
Background , , ,
;
Foreground ,
;
Opacity ( UIElement)
.
0 1.
Background Foreground Brush,
. , ,
,
SolidBrush:

67

Windows 8 C#
<StackPanel>
<Button Background="#FFFF0000" Foreground="#FF00FF00"
Content="Hello"></Button>
<Button Background="Red" Foreground="LightGreen"
Content="Hello"></Button>
<Button Content="Hello">
<Button.Background>
<SolidColorBrush Color="Red"></SolidColorBrush>
</Button.Background>
<Button.Foreground>
<SolidColorBrush Color="LightGreen"></SolidColorBrush>
</Button.Foreground>
</Button>
</StackPanel>
:
,
XAML, SolidColorBrush.
C# :

btn.Background = new SolidColorBrush(Colors.Red);


Colors ,
.
,
:
FontFamily , ;
FontSize Silverlight;
FontStyle , Normal Italic;
FontWeight , Bold;
FontStretch
.

OpenType,

,
Arial,
:

68

2.
<Button Background="Red" Foreground="LightGreen" Content="Hello"
FontFamily="Arial"
FontSize="16"
FontStyle="Italic"
FontWeight="Bold">
</Button>
,
:
Width ;
Height ;
Padding ;
Margin .

WinRT . ,
ToggleSwitch. :
Button ,
UIElement Click;
ToggleButton ,
. : .
,
Checked;
RepeatButton ,
Click,
, ;
CheckBox ToggleButton
. ToggleButton,
,
IsThreeState true;
RadioButton
CheckBox,
, ;
HyperlinkButton
.
;
69

Windows 8 C#
ToggleSwitch
Touch-,
. CheckBox,
.
ToggleSwitch ,
.
:

<ToggleSwitch OffContent="" OnContent=""></ToggleSwitch>


:

. 2.7.
Windows Phone
.
,
RadioButton:

<StackPanel>
<RadioButton Content="Choice 1" IsChecked="True"
GroupName="Group 1" Margin="5">
</RadioButton>
<RadioButton Content="Choice 1" IsChecked="False"
GroupName="Group 1" Margin="5">
</RadioButton>
<RadioButton Content="Choice 1" IsChecked="False"
GroupName="Group 1" Margin="5">
</RadioButton>
<RadioButton Content="Choice 1" IsChecked="False"
GroupName="Group 1" Margin="5">
</RadioButton>
</StackPanel>

70

2.
:

. 2.8.
, XAML ,
( )
. ,
:

<Button MaxHeight="150" MaxWidth="200">


<Button.Content>
<MediaElement Source="Wildlife.wmv"></MediaElement>
</Button.Content>
</Button>

. 2.9.

71

Windows 8 C#


Windows Runtime ,
:
TextBox
;
PasswordBox ;
RichEditBox .
, TextBox PasswordBox,
:
AcceptsReturn ;
IsReadOnly , ;
SelectedText ;
SelectionLength
;
SelectionStart ,
;
SelectionBackground ;
SelectionForeground ;
TextWraping , ,
.

<TextBox AcceptsReturn="True" TextWrapping="Wrap" Width="300" Height="200">


</TextBox>
TextBox TextBlock,
.

.
,
RichTextEdit RichTextBlock.
, .
. ,
Paragraph,
. ,
:
72

2.
Run ;
Span ;
Bold ;
LineBreak ;
Italic ;
Underline ;
HyperLink ,
ReadOnly RichTextArea;
InlineUIContainer ,
UIElement.
RichTextBlock,
:

<RichTextBlock HorizontalAlignment="Left"
Name="rArea" VerticalAlignment="Top"
Height="300" Width="400" >
<Paragraph>
<Bold>This is a bold text</Bold>
<LineBreak></LineBreak>
<Underline>This is an underline text</Underline>
<LineBreak></LineBreak>
<Italic>This is an italic text</Italic>
<LineBreak></LineBreak>
This is a button:
<InlineUIContainer>
<Button Content="Button"></Button>
</InlineUIContainer>
</Paragraph>
</RichTextBlock>
:

. 2.10.
73

Windows 8 C#
, RichTextBlock
C#. :

Bold b = new Bold();


b.Inlines.Add("This is a bold text");
Italic i = new Italic();
i.Inlines.Add("This is an italic text");
Underline u = new Underline();
u.Inlines.Add("This is an underlined text");
Paragraph myPar = new Paragraph();
myPar.Inlines.Add(b);
myPar.Inlines.Add(new LineBreak());
myPar.Inlines.Add(i);
myPar.Inlines.Add(new LineBreak());
myPar.Inlines.Add(u);
rArea.Blocks.Add(myPar);

,
Silverlight,
Windows Presentation Foundation, ,
, .
, Windows Runtime
:
ListBox
;
ComboBox
.
:
Items ListBoxItem,
ListBox;
ItemsSource ListBox ,
IEnumerable;
74

2.
DisplayMemberPath ,
ItemsSource,
ListBox. ,
ToString;
ItemTempate .
, ;
SelectedItem(s) () ListBox.
,
, ListBox.
;
SelectedValue ( ).
ListBox
:

<ListBox Name="myList" Width="200" Height="100" Background="White">


<ListBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsActive}"
Content="{Binding Name}" Foreground="Black">>
</CheckBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
.
,
:
public sealed partial class BlankPage : Page
{
public BlankPage()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private void Page_Loaded_1(object sender, RoutedEventArgs e)
75

Windows 8 C#
{
List<Employee> l = new List<Employee>();
Employee emp = new Employee();
emp.Name = "Sergiy Baydachnyy";
emp.IsActive = true;
l.Add(emp);
emp = new Employee();
emp.Name = "Viktor Baydachnyy";
emp.IsActive = false;
l.Add(emp);
myList.ItemsSource = l;
}
public class Employee
{
public string Name { get; set; }
public bool IsActive { get; set; }
}
}
ComboBox:
<ComboBox Name="myList" Background="White" Height="100">
<ComboBox.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsActive}"
Content="{Binding Name}" Foreground="Black">
</CheckBox>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
,
, . ,
ComboBox ,
,
.
, .
76

2.
Windows Runtime
,
.
,
Metro, .
.
:
FlipView
.
.
;
ListView
. ,
Metro ( , .);
GridView .

;
SemanticZoom
.
.

FlipView. , :

<StackPanel x:Name="LayoutRoot">
<FlipView>
<FlipView.Items>
<Image Source="dsc01707.jpg"></Image>
<Image Source="dsc01707.jpg"></Image>
</FlipView.Items>
</FlipView>
</StackPanel>
.
,

, , .
ListView ,
ListBox, ListBox
ListView, :
77

Windows 8 C#
<ListView Name="myList" Width="200" Height="300" Background="White">
<ListView.ItemTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsActive}"
Content="{Binding Name}" Foreground="Black">
</CheckBox>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
, ,
Metro:

. 2.11.

ListView (, ),
IsItemClickEnabled,
ItemClick,
. false.
GridView,
Grid Application
. :
78

2.
<GridView
x:Name="itemGridView"
AutomationProperties.AutomationId="ItemGridView"
AutomationProperties.Name="Grouped Items"
Margin="120,0,40,60"
ItemsSource="{Binding Source={StaticResource groupedItemsViewSource}}"
ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
SelectionMode="None"
IsItemClickEnabled="True"
ItemClick="ItemView_ItemClick">
<GridView.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</GridView.ItemsPanel>
<GridView.GroupStyle>
<GroupStyle>
<GroupStyle.HeaderTemplate>
<DataTemplate>
<Grid Margin="0,0,0,20">
<Button
AutomationProperties.Name="Group Title"
Content="{Binding Title}"
Click="Header_Click"
Style="{StaticResource TextButtonStyle}"/>
</Grid>
</DataTemplate>
</GroupStyle.HeaderTemplate>
<GroupStyle.Panel>
<ItemsPanelTemplate>
<VariableSizedWrapGrid
Orientation="Vertical" Margin="0,0,80,0"/>
</ItemsPanelTemplate>
</GroupStyle.Panel>
</GroupStyle>
</GridView.GroupStyle>
</GridView>

79

Windows 8 C#
,
:
GroupStyle.Panel
.
VariableSizedWrapPanel ( WrapPanel),

() ,
;
GroupStyle.HeaderTemplate .
,
;
GridView.ItemsPanel
.
StackPanel.
, ,
, :

. 2.12.
SemanticZoom.
, ,
.
ZoomedInView ZoomedOutView.
ListView GridView .

80

2.
SemanticZoom
Windows 8, All Applications Application Bar.
:

. 2.13.
:

. 2.14.
.
81

Windows 8 C#

ScrollViewer
, ,
ScrollViewer.
,
.

.
. :
ZoomMode ;
MaxZoomFactor
;

MinZoomFactor

ZoomSnapPoints
.

, ,
, ScrollView .
, .

WinRT ,
, Slider, ScrollBar ProgressBar.
RangeBase :
Minimum ;
Maximum ;
Value
ProgressBar.
, Slider ScrollBar
, ProgressBar
, .
, Slider:

82

2.
<StackPanel x:Name="LayoutRoot">
<MediaElement Source="WildLife.wmv" Width="400" Height="300">
<MediaElement.Projection>
<PlaneProjection
RotationX=
"{Binding Value, ElementName=rotateXSlider, Mode=OneWay}"
RotationY=
"{Binding Value, ElementName=rotateYSlider, Mode=OneWay}"
RotationZ=
"{Binding Value, ElementName=rotateZSlider, Mode=OneWay}">
</PlaneProjection>
</MediaElement.Projection>
</MediaElement>
<Slider Width="400" Minimum="0" Maximum="360"
Name="rotateXSlider">
</Slider>
<Slider Width="400" Minimum="0" Maximum="360"
Name="rotateYSlider">
</Slider>
<Slider Width="400" Minimum="0" Maximum="360"
Name="rotateZSlider">
</Slider>
</StackPanel>

ProgressRing
ProgressRing,
.
,
.
IsActive, false
. , , IsActive
true.
, :

<Grid Background="White">
<ProgressRing IsActive="true"></ProgressRing>
</Grid>

83

Windows 8 C#

ToolTip
ToolTip,
.
UIElement , , :

<Button Content="Detach" Width="100">


<ToolTipService.ToolTip>
<ToolTip Placement="Right">
<ToolTip.Content>
<MediaElement Source="4.wmv"></MediaElement>
</ToolTip.Content>
</ToolTip>
</ToolTipService.ToolTip>
</Button>
ToolTip ,
. Placement.

Application Bar
, AppBar ,
, . , AppBar

, ,
- .
, AppBar ?
AppBar, Windows
8 ,
. :

. 2.15.

84

2.
. Internet
Explorer, .
,
. ,
, (
, ):

. 2.16.
, ,
,
. ,
,
.
,
.
, AppBar
, .
Windows Phone ,
WP 7 Refresh, Home .,
AppBar ( WP 7).
.
(
Page):

85

Windows 8 C#
<Page.TopAppBar>
<AppBar x:Name="BottomAppBar" Height="88">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Button Grid.Column="0"
Style="{StaticResource HomeAppBarButtonStyle}"/>
<StackPanel Grid.Column="1"
Orientation="Horizontal" HorizontalAlignment="Right">
<Button Style="{StaticResource SaveAppBarButtonStyle}" />
</StackPanel>
</Grid>
</AppBar>
</Page.TopAppBar>
, AppBar,
TopAppBar BottomAppBar Page.
AppBar , . ,
AppBar, . AppBar
:

. 2.17.
,
, StandardStyles.xaml.
AppBarButtonStyle,
Based On . Home:

<Style x:Key="HomeAppBarButtonStyle" TargetType="Button"


BasedOn="{StaticResource AppBarButtonStyle}">
<Setter Property="AutomationProperties.AutomationId"
Value="HomeAppBarButton"/>
<Setter Property="AutomationProperties.Name"
86

2.
Value="Home"/>
<Setter Property="Content" Value="&#xE10F;"/>
</Style>
, ID, .
,
Segoe UI Symbols. ,
.
Character
Map, :

. 2.18.

87

Windows 8 C#


Windows 8 , .
,
,
.
, WinRT .
, ,
, .
:
, (, );
, (, , );
, (, ).
. ,

.
, ,
.
(, )
. .
, .
:
Tapped .
,
( );
DoubleTapped , ,
. Platform Preview ,
- ,
;
Holding ,
.
,
;
RightTapped ,
,
.
, RightTapped
Holding
.
88

2.
, ,
true , IsTapEnabled,
IsDoubleTapEnabled, IsHoldingEnabled, IsRightTapEnabled .
Windows 8
,
true.
,
PointerDeviceType.
: Mouse, Touch, Pen. ,
.
Holding,
. ,
:
private void Grid_Holding(object sender, HoldingRoutedEventArgs e)
{
switch (e.HoldingState)
{
case Windows.UI.Input.HoldingState.Started:
. . . . .
break;
case Windows.UI.Input.HoldingState.Completed:
. . . . .
break;
case Windows.UI.Input.HoldingState.Canceled:
. . . . .
break;
}
}
, -
( , )
, ,
.
Canceled.

89

Windows 8 C#
. :
ManipulationStarting -
. ,
;
ManipulationStarted ,
;
ManipulationDelta ,
.
(, , )
;
ManipulationCompleted
;
ManipulationInertiaStarting ,
.
.
, , ,
. , .
, ,
.
, ,
( ).
()
ManipulationMode. ,
( ) .
ManipulationStarting.
Mode.
, .
ManipulationDelta.
Delta,
, , :
Rotation ( , ,
);
Expansion
.
;
Translation X Y.
;
Scale
.
90

2.
,
.
,
.
XAML:

<Canvas Background="{StaticResource ApplicationPageBackgroundBrush}">


<Image Source="DSC01707.JPG" Height="300" Width="400" Name="img"
ManipulationMode="Rotate" "
ManipulationDelta="Image_ManipulationDelta">
</Image>
</Canvas>
,
, Rotation (
Rotation XAML):

public BlankPage()
{
this.InitializeComponent();
RotateTransform tr = new RotateTransform()
{
Angle = 0,
CenterX = img.ActualWidth / 2,
CenterY = img.ActualHeight / 2
};
img.RenderTransform = tr;
}
private void Image_ManipulationDelta(object sender,
ManipulationDeltaRoutedEventArgs e)
{
RotateTransform rt = img.RenderTransform as RotateTransform;
rt.Angle += e.Delta.Rotation * 180 / Math.PI;
e.Handled = true;
}
91

Windows 8 C#
:
PointerPressed ;
PointerReleased ;
PointerWheelChanged ,
( );
PointerMoved
( );
PointerEntered ,
;
PointerExited ,
;
PointerCaptureLost ,
(, ,
Filled);
PointerCanceled , .
,
. XAML Canvas:

<Canvas Name="LayoutRoot"
Background="{StaticResource ApplicationPageBackgroundBrush}"
PointerPressed="Canvas_PointerPressed_1"
PointerMoved="Canvas_PointerMoved_1"
PointerReleased="LayoutRoot_PointerReleased">
</Canvas>

:
Point? startPoint = null;
private void Canvas_PointerPressed_1(object sender, PointerEventArgs e)
{
startPoint = e.GetCurrentPoint(LayoutRoot).Position;
}
private void Canvas_PointerMoved_1(object sender, PointerEventArgs e)
{
if (startPoint != null)
92

2.
{
Line l = new Line();
l.X1 = ((Point)startPoint).X;
l.Y1 = ((Point)startPoint).Y;
startPoint = e.GetCurrentPoint(LayoutRoot).Position;
l.X2 = ((Point)startPoint).X;
l.Y2 = ((Point)startPoint).Y;
l.Stroke = new SolidColorBrush(Colors.Red);
LayoutRoot.Children.Add(l);
}
}
private void LayoutRoot_PointerReleased(object sender, PointerEventArgs e)
{
startPoint = null;
}

, ,
Windows 8 . ,
Metro
. , , ,
, Current Window.
,
Content, .
, Activate.
,
, , Content
Activate. Windows 8 (Platform Preview)
. ,
,
..
Frame,
.
App.xaml.cs. :
93

Windows 8 C#
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
var rootFrame = new Frame();
rootFrame.Navigate(typeof(BlankPage));
Window.Current.Content = rootFrame;
Window.Current.Activate();
}
, Frame,
Content. Navigate
Frame BlankPage ( ),
Activate. ,
Frame , ,
, :
CacheSize ,
;
CanGoBack ,
( );
CanGoForward ,
,
;
GoBack ;
GoForward ;
Navigated , ;
Navigating , ;
NavigationFailed , ,
(, );
NavigationStopped , ,
StopLoading
;
StopLoading
;
Navigate ,
.

94

2.

.
,
LayoutAwarePage.cs, .
:

protected virtual void GoHome(object sender, RoutedEventArgs e)


{
if (this.Frame != null)
{
while (this.Frame.CanGoBack) this.Frame.GoBack();
}
}
, Home
. ,

. Frame
Page, .

95

3.

Windows 8 C#


,
. ,
, , , . .
.
, .
, .
<StackPanel>
<Button Width="100" Height="50"
Background="Green"
Content="Button 1" Margin="5" FontFamily="Arial"
FontSize="12" FontWeight="Bold"
Foreground="Blue" BorderThickness="3">
</Button>
<Button Width="100" Height="50"
Background="Green"
Content="Button 2" Margin="5" FontFamily="Arial"
FontSize="12" FontWeight="Bold"
Foreground="Blue" BorderThickness="3">
</Button>
<Button Width="100" Height="50"
Background="Green"
Content="Button 3" Margin="5" FontFamily="Arial"
FontSize="12" FontWeight="Bold"
Foreground="Blue" BorderThickness="3">
</Button>
<Button Width="100" Height="50"
Background="Green"
Content="Button 4" Margin="5" FontFamily="Arial"
FontSize="12" FontWeight="Bold"
Foreground="Blue" BorderThickness="3">
</Button>
</StackPanel>
98

3.
, ,
. ,
. ,
.
XAML
Style.
, ,
,
( ).
, Style .

Page.

<Page.Resources>
<Style x:Key="buttonStyle" TargetType="Button">
<Setter Property="Background" Value="Green"></Setter>
<Setter Property="Margin" Value="5"></Setter>
<Setter Property="FontFamily" Value="Arial"></Setter>
<Setter Property="FontSize" Value="12"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
<Setter Property="Foreground" Value="Blue"></Setter>
<Setter Property="BorderThickness" Value="3"></Setter>
</Style>
</Page.Resources>
, , ,
.
, TargetType , .
Setter
. XAML .
<StackPanel>
<Button Width="100" Height="50"
Style="{StaticResource buttonStyle}" Content="Button 1">
</Button>
<Button Width="100" Height="50"
Style="{StaticResource buttonStyle}" Content="Button 2">
</Button>

99

Windows 8 C#
<Button Width="100" Height="50"
Style="{StaticResource buttonStyle}" Content="Button 3">
</Button>
<Button Width="100" Height="50"
Style="{StaticResource buttonStyle}" Content="Button 4">
</Button>
</StackPanel>
, . ,
,
( ). ,
.
<Page.Resources>
<Style TargetType="Button">
<Setter Property="Background" Value="Green"></Setter>
<Setter Property="Margin" Value="5"></Setter>
<Setter Property="FontFamily" Value="Arial"></Setter>
<Setter Property="FontSize" Value="12"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
<Setter Property="Foreground" Value="Blue"></Setter>
<Setter Property="BorderThickness" Value="3"></Setter>
</Style>
</Page.Resources>
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<StackPanel>
<Button Width="100" Height="50"
Content="Button 1">
</Button>
<Button Width="100" Height="50"
Content="Button 2">
</Button>
<Button Width="100" Height="50"
Content="Button 3">
</Button>
<Button Width="100" Height="50"
Content="Button 4">
</Button>
</StackPanel>
</Grid>
100

3.
,
,
.
, , Visual Studio
StandardStyles.xaml,
. , ,
BackButtonStyle.
<StackPanel>
<Button Width="100" Height="50"
Content="Button 1" Style="{StaticResource BackButtonStyle}">
</Button>
<Button Width="100" Height="50"
Content="Button 2" Style="{StaticResource BackButtonStyle}">
</Button>
<Button Width="100" Height="50"
Content="Button 3" Style="{StaticResource BackButtonStyle}">
</Button>
<Button Width="100" Height="50"
Content="Button 4" Style="{StaticResource BackButtonStyle}">
</Button>
</StackPanel>
.

. 3.1.
101

Windows 8 C#
, . ,
,
, . .
, .
.

BasedOn-
XAML Windows Runtime BasedOn-.

( )
. BasedOn.

<Style x:Key="baseStyle" TargetType="Button" >


<Setter Property="Width" Value="100"></Setter>
</Style>
<Style x:Key="btnStyleRus"
BasedOn="{StaticResource baseStyle}" TargetType="Button">
<Setter Property="Foreground" Value="Blue"></Setter>
<Setter Property="Content" Value=""></Setter>
</Style>
<Style x:Key="btnStyle"
BasedOn="{StaticResource baseStyle}" TargetType="Button">
<Setter Property="Foreground" Value="Green"></Setter>
<Setter Property="Content" Value="Button"></Setter>
</Style>
( ),
.

102

3.

. ,
, XAML-.
Resources, Page.
XAML, FrameworkElement,
(Application).
XAML- . ,
, , .
, Resources ,
, XAML.
,
, ,
.
,
.
.

<Page.Resources>
<LinearGradientBrush x:Key="myBrush">
<GradientStop Color="Red" Offset="0"></GradientStop>
<GradientStop Color="Green" Offset="1"></GradientStop>
</LinearGradientBrush>
</Page.Resources>
<StackPanel>
<Button Width="100" Height="50"
Background="{StaticResource myBrush}"
Content="Button 1" Margin="5">
</Button>
</StackPanel>
, (
) myBrush.
. ,
StaticResource.
.
Page,
.
.
103

Windows 8 C#
, ,
StackPanel.

<StackPanel>
<StackPanel.Resources>
<LinearGradientBrush x:Key="myBrush">
<GradientStop Color="Red" Offset="0"></GradientStop>
<GradientStop Color="Green" Offset="1"></GradientStop>
</LinearGradientBrush>
</StackPanel.Resources>
<Button Width="100" Height="50"
Background="{StaticResource myBrush}"
Content="Button 1" Margin="5">
</Button>
</StackPanel>
, ,
. , ,
.
, ,
.
, ,
.
.

<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Application4">
<Application.Resources>
<LinearGradientBrush x:Key="myBrush">
<GradientStop Color="Red" Offset="0"></GradientStop>
<GradientStop Color="Green" Offset="1"></GradientStop>
</LinearGradientBrush>
</Application.Resources>
</Application>

104

3.



ResourceDictionary.
RD1.xaml.

<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<LinearGradientBrush x:Key="myBrush">
<GradientStop Color="Red" Offset="0"></GradientStop>
<GradientStop Color="Green" Offset="1"></GradientStop>
</LinearGradientBrush>
</ResourceDictionary>

ResourceDictionary.

<Application
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Application4">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="RD1.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
. .
, StandardStyles.xaml
,
App.xaml.
,
.

105

Windows 8 C#


XAML, ,
,
. ,
. , ,
, ,
,
. .
, WPF Silverlight.
,
.
<Button Width="100" Height="50"
Content="Button 1" Margin="5">
, ,
Content. ,
Hello!, !.
en-US ru-RU.
( ),
.
Resources.resw.

. 3.2.
106

3.
. ,
.
,
. , .

. 3.3.
myTxt.Content.
, Windows 8
, .
, myTxt ,
x:Uid.

<Button Width="100" Height="50" x:Uid="myTxt"


Content="Button 1" Margin="5">
</Button>
, ,
. ,
Package.appmanifest
View Code . Resources
, .

<Resources>
<Resource Language="en-us"/>
<Resource Language="ru-ru"/>
</Resources>
. , ,
. , Language
(Control Panel) Windows 8.

107

Windows 8 C#

. 3.4.
, , .
!.
,
( , .),
ResourceLoader.

ResourceLoader rl = new ResourceLoader();


string s = rl.GetString(Test");
, ,
(
), .
.

108

4.
,

Windows 8 C#


, ,
. ,
.
, XAML, ,

.
Windows Runtime :
Rectangle ;
Ellipse ( );
Line ;
Polygon ;
Polyline ;
Path .

Shape, , , FrameworkElement.
, ,
,
, .
, Shape ,
. .
Stroke , .
StrokeThickness .
Fill ,
.
, ,
.
StrokeDashArray double,
.
.
StrokeDashCap ()
(). : Float, Round,
Squared, Triangle.
StrokeDashOffset .
StrokeEndLineCap
110

4. ,
( ). : Float, Round, Squared,
Triangle.
StrokeStartLineCap
( ). : Float, Round, Squared,
Triangle.
StrokeLineJoin .
: Bevel, Miter, Round.

Rectangle.
<StackPanel x:Name="LayoutRoot" Background="White">
<Rectangle Width="300" Height="100" Stroke="Black"
StrokeThickness="10"
RadiusX="25" RadiusY="25" Margin="5"></Rectangle>
<Rectangle Width="300" Height="100" Stroke="Black"
StrokeThickness="10" RadiusX="25" RadiusY="25"
StrokeDashArray="5,2,3,2" Margin="5"></Rectangle>
<Rectangle Width="300" Height="100" Stroke="Black"
StrokeThickness="10" RadiusX="25" RadiusY="25"
StrokeDashArray="5,2,3,2" StrokeDashCap="Triangle"
Margin="5"></Rectangle>
</StackPanel>
.

. 4.1.

111

Windows 8 C#
, ,
Width Height, .
RadiusX RadiusY .
.
, 10.
StrokeDashArray,
5 3 ,
2 .
.
Ellipse .
Width Height,
.

<Ellipse Width="300" Height="100" StrokeThickness="10"


Stroke="Black" Fill="Red">
</Ellipse>
Fill,
.
SolidColorBrush, . Fill
, .
.

. 4.2.
Line,
.
.

<Line X1="0" Y1="0" X2="100" Y2="100" Stroke="Black"></Line>

112

4. ,
: ?
.
Canvas, ,
, ,
.
Polygon,
.

<Polygon Points="0,50,50,0,100,0,150,50,150,100,100,150,50,150,0,100"
Stroke="Black" StrokeThickness="5">
</Polygon>
, .
, .
.

. 4.3.
Polyline ,
. .

<Polyline Points="0,50,50,0,100,0,150,50,150,100,100,150,50,150,0,100"
Stroke="Black" StrokeThickness="5">
</Polyline>
-.

113

Windows 8 C#

. 4.4.
, Path.
. ,
.
, Data.
, ,
, .
.

<Path Stroke="Black" StrokeThickness="5"


Data="M 10,100 C 10,300 300,-200 300,100">
</Path>
,
.

. 4.5.

114

4. ,
, Data ,
,
. . .
,
Path.
M
L .
H .
V .
C
, .
.
Q
, .
S
.
T .
A .
: , , (0 1),
(0 1), .
Z ,
.
. ,
, .

115

Windows 8 C#

, ,
.
.

SolidColorBrush
(Red,
Green . .).
SolidColorBrush.
,
. , .

<Rectangle Width="300" Height="100" Fill="Red"></Rectangle>


<Rectangle Width="300" Height="100">
<Rectangle.Fill>
<SolidColorBrush Color="Red"></SolidColorBrush>
</Rectangle.Fill>
</Rectangle>
, C#.

rect.Fill = new SolidColorBrush(Colors.Red);

LinearGradientBrush
LinearGradientBrush
.

.

<Rectangle Width="300" Height="300">


<Rectangle.Fill>
<LinearGradientBrush>
<GradientStop Color="Red" Offset="0"></GradientStop>
116

4. ,
<GradientStop Color="Green" Offset="1"></GradientStop>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
, , StartPoint
EndPoint. ,
, 1.

<Rectangle Name="rect" Width="300" Height="300">


<Rectangle.Fill>
<LinearGradientBrush StartPoint="0,1" EndPoint="1,0">
<GradientStop Color="Red" Offset="0"></GradientStop>
<GradientStop Color="White" Offset="0.5"></GradientStop>
<GradientStop Color="Green" Offset="1"></GradientStop>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
,
. ,
,
.

ImageBrush

. ImageBrush.
ImageSource Stretch.
, ,
( ).
, ImageBrush .

<TextBlock Text="Hello" FontSize="170" FontWeight="Bold">


<TextBlock.Foreground>
<ImageBrush ImageSource="Tulips.jpg"></ImageBrush>
</TextBlock.Foreground>
</TextBlock>

117

Windows 8 C#


WinRT .
, ,
, Path
Clip UIElement.
,
, ,
. .
LineGeometry .
.
EllipseGeometry .
, .
RectangleGeometry .
.

<Path Stroke="Black" StrokeThickness="2" >


<Path.Data>
<EllipseGeometry RadiusX="100" RadiusY="100"
Center="100,100"/>
</Path.Data>
</Path>
.

PathGeometry.
.
PathFigure.
Path,
.
.
, PathGeometry.
ArcSegment .
LineSegment .
BezierSegment .
PolyLineSegment
.
118

4. ,
PolyBezierSegment
.

QuadraticBezierSegment .
PolyQuadraticBezierSegment
.
, PathGeometry.
<Path Stroke="Black" StrokeThickness="1" >
<Path.Data>
<PathGeometry>
<PathGeometry.Figures>
<PathFigure StartPoint="10,50">
<PathFigure.Segments>
<BezierSegment Point1="100,0"
Point2="200,200"
Point3="300,100"/>
<LineSegment Point="400,100" />
<ArcSegment Size="50,50" RotationAngle="45"
IsLargeArc="True" SweepDirection="Clockwise"
Point="200,100"/>
</PathFigure.Segments>
</PathFigure>
</PathGeometry.Figures>
</PathGeometry>
</Path.Data>
</Path>
.

. 4.6.
,
, GeometryGroup.
119

Windows 8 C#


Windows Runtime , UIElement,
.
() .
.
RotateTransform
.
ScaleTransform
.
ScaleX ScaleY, ,
. 0
1, , 1, .
SkewTransform X Y.
AngleX AngleY.
TranslateTransform
X Y.
MatrixTransform
.
,

RenderTransform.
, RenderTransform
TransformGroup,
. ,
,
. .

<StackPanel x:Name="LayoutRoot" Background="White">


<Rectangle Width="200" Height="100" Fill="Red">
<Rectangle.RenderTransform>
<TransformGroup>
<RotateTransform Angle=
"{Binding Value, ElementName=rotateSlider, Mode=OneWay}"
CenterX="100" CenterY="50">
</RotateTransform>
<ScaleTransform CenterX="100" CenterY="50"
120

4. ,
ScaleX=
"{Binding Value, ElementName=scaleXSlider, Mode=OneWay}"
ScaleY=
"{Binding Value, ElementName=scaleYSlider, Mode=OneWay}">
</ScaleTransform>
<SkewTransform CenterX="100" CenterY="50"
AngleX=
"{Binding Value, ElementName=skewXSlider, Mode=OneWay}"
AngleY=
"{Binding Value, ElementName=skewYSlider, Mode=OneWay}">
</SkewTransform>
<TranslateTransform X=
"{Binding Value, ElementName=translateXSlider, Mode=OneWay}"
Y=
"{Binding Value, ElementName=translateYSlider, Mode=OneWay}">
</TranslateTransform>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
<Slider Width="200" Name="rotateSlider" Minimum="0"
Maximum="360">
</Slider>
<Slider Width="200" Name="scaleXSlider" Minimum="0"
Maximum="2" Value="1">
</Slider>
<Slider Width="200" Name="scaleYSlider" Minimum="0"
Maximum="2" Value="1">
</Slider>
<Slider Width="200" Name="skewXSlider" Minimum="-180"
Maximum="180" Value="0">
</Slider>
<Slider Width="200" Name="skewYSlider" Minimum="-180"
Maximum="180" Value="0">
</Slider>
<Slider Width="200" Name="translateXSlider"
Minimum="-100" Maximum="100" Value="0">
</Slider>
<Slider Width="200" Name="translateYSlider"
Minimum="-100" Maximum="100" Value="0">
</Slider>
</StackPanel>

121

Windows 8 C#
:

. 4.7.
,
, .

CompositeTransform
CompositeTransform,
.

.
,
, .
, .

<StackPanel x:Name="LayoutRoot" Background="White">


<Rectangle Width="200" Height="100" Fill="Red">
<Rectangle.RenderTransform>
122

4. ,
<CompositeTransform CenterX="100" CenterY="50"
ScaleX=
"{Binding Value, ElementName=scaleXSlider, Mode=OneWay}"
ScaleY=
"{Binding Value, ElementName=scaleYSlider, Mode=OneWay}"
Rotation=
"{Binding Value, ElementName=rotateSlider, Mode=OneWay}"
SkewX=
"{Binding Value, ElementName=skewXSlider, Mode=OneWay}"
SkewY=
"{Binding Value, ElementName=skewYSlider, Mode=OneWay}"
TranslateX=
"{Binding Value, ElementName=translateXSlider, Mode=OneWay}"
TranslateY=
"{Binding Value, ElementName=translateYSlider, Mode=OneWay}">
</CompositeTransform>
</Rectangle.RenderTransform>
</Rectangle>
<Slider Width="200" Name="rotateSlider" Minimum="0"
Maximum="360">
</Slider>
<Slider Width="200" Name="scaleXSlider" Minimum="0"
Maximum="2" Value="1">
</Slider>
<Slider Width="200" Name="scaleYSlider" Minimum="0"
Maximum="2" Value="1">
</Slider>
<Slider Width="200" Name="skewXSlider" Minimum="-180"
Maximum="180" Value="0">
</Slider>
<Slider Width="200" Name="skewYSlider" Minimum="-180"
Maximum="180" Value="0">
</Slider>
<Slider Width="200" Name="translateXSlider"
Minimum="-100" Maximum="100" Value="0">
</Slider>
<Slider Width="200" Name="translateYSlider"
Minimum="-100" Maximum="100" Value="0">
</Slider>
</StackPanel>
,
.
123

Windows 8 C#


PlaneProjection,

. ,
(Border),
,
.
PlaneProjection MediaElement,
.

<StackPanel x:Name="LayoutRoot" Background="White">


<MediaElement Source="WildLife.wmv" Width="400" Height="300">
<MediaElement.Projection>
<PlaneProjection
RotationX=
"{Binding Value, ElementName=rotateXSlider, Mode=OneWay}"
RotationY=
"{Binding Value, ElementName=rotateYSlider, Mode=OneWay}"
RotationZ=
"{Binding Value, ElementName=rotateZSlider, Mode=OneWay}">
</PlaneProjection>
</MediaElement.Projection>
</MediaElement>
<Slider Width="400" Minimum="0" Maximum="360"
Name="rotateXSlider">
</Slider>
<Slider Width="400" Minimum="0" Maximum="360"
Name="rotateYSlider">
</Slider>
<Slider Width="400" Minimum="0" Maximum="360"
Name="rotateZSlider">
</Slider>
</StackPanel>
RotationX, RotationY, RotationZ,

.
.

124

4. ,

. 4.8.
, , ,
, RenderTransform.
PlaneProjection ,
,
.
. : CenterOfRotationX,
CenterOfRotationY,
CenterOfRotationZ,
LocalOffsetX,
LocalOffsetY,
LocalOffsetZ, GlobalOffsetX, GlobalOffsetY, GlobalOffsetZ.

125

Windows 8 C#



Windows Runtime
, UIElement.
, ,
C#.
,
.
DoubleAnimation
DoubleAnimation
double. From
To, .
,
By,
.
ColorAnimation
ColorAnimation Color.
. ,
, Fill Stroke
, , .
, ,
double .
PointAnimation
PointAnimation .
, DoubleAnimation,
.
,
.
Duration
:: (00:00:03 3 ).
,
.
BeginTime ,
,
, .
126

4. ,
SpeedRatio n .

, .
AutoReverse
.
5 ,
AutoReverse true
10 .
RepeatBehavior ,
.
.
,
, .
Forever .
Nx N ,
. ,
.
,
.
,
StoryBoard. . ,
StoryBoard.TargetName StoryBoard.
TargetProperty ,
, , .
StoryBoard,
.

<Storyboard>
<DoubleAnimation
Storyboard.TargetName="myButton"
Storyboard.TargetProperty="(Canvas.Left)"
To="200" Duration="0:0:5" AutoReverse="True" />
</Storyboard>
, ,
.

127

Windows 8 C#


:
XAML ;
C#.
XAML,
EventTrigger, Triggers
. - ,
EventTrigger ,
. Triggers
, WinRT EventTrigger,
Loaded ( UserControl.Loaded
.Loaded, Canvas.Loaded).
.
<Button x:Name="myButton" Canvas.Top="0" Canvas.Left="0" Width="100"
Height="50" Content="Hello">
<Button.Triggers>
<EventTrigger RoutedEvent="UserControl.Loaded">
<BeginStoryboard>
<Storyboard>
<DoubleAnimation
Storyboard.TargetName="myButton"
Storyboard.TargetProperty="(Canvas.Left)"
To="200" Duration="0:0:5" AutoReverse="True" />
</Storyboard>
</BeginStoryboard>
</EventTrigger>
</Button.Triggers>
</Button>
, ,
StoryBoard , ,
.
,
. StoryBoard ,
:
Begin
Stop
Pause
, Completed,
.
128

4. ,



, .
, ,
, . Silverlight
, .
:
DoubleAnimationUsingKeyFrames
PointAnimationUsingKeyFrames
ColorAnimationUsingKeyFrames
,
UsingKeyFrames.
DoubleAnimationUsingKeyFrames.
<Storyboard>
<DoubleAnimationUsingKeyFrames Duration="0:0:5"
AutoReverse="True" Storyboard.TargetName="myButton"
Storyboard.TargetProperty="(Canvas.Left)">
<LinearDoubleKeyFrame KeyTime="0:0:2"
Value="70"></LinearDoubleKeyFrame>
<LinearDoubleKeyFrame KeyTime="0:0:5"
Value="100"></LinearDoubleKeyFrame>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
,
LinearDoubleKeyFrame. 70
30 .

LinearDoubleKeyFrame,

DiscreteDoubleKeyFrame SplineDoubleKeyFrame.
,
.
, .

.

129

Windows 8 C#

ObjectAnimationUsingKeyFrame,
. ,
,
(
).


.
,
.
, , ,
. ,
.
,
, .
Windows Runtime
. ,
, .

<UserControl x:Class="SilverlightApplication52.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300" Loaded="UserControl_Loaded">
<UserControl.Resources>
<Storyboard x:Name="sb1">
<DoubleAnimation From="0" To="250"
Storyboard.TargetName="el1"
Storyboard.TargetProperty="(Canvas.Top)"
Duration="0:0:5">
<DoubleAnimation.EasingFunction>
<BounceEase Bounces="10"
EasingMode="EaseOut" Bounciness="2">
</BounceEase>
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
</Storyboard>
</UserControl.Resources>
<Canvas x:Name="LayoutRoot" Background="White">
130

4. ,
<Ellipse Fill="Blue" Width="50" Height="50" x:Name="el1"></Ellipse>
</Canvas>
</UserControl>
, BounceEase
, .
11 .
: ExponentialEase, PowerEase, QuadraticEase, BackEase, BounceEase,
CircleEase, CubicEase, ElasticEase, QuarticEase, QuinticEase, SineEase.
, .
, EasingMode
.


,
Metro .
, .
, , .

, Windows Runtime ,
(GridView,
FlipView, ListView .), ,
.
,
ItemsControl,
, .
.



.
.
AddDeleteThemeTransition
( ).
()
( ) .
131

Windows 8 C#
ContentThemeTransition ,
(Content) .

.
,
Content ( ).
.
EntranceThemeTransition
.
ReorderThemeTransition ,
, , (,
).
RepositionThemeTransition
.
EdgeUIThemeTransition
().

ContentThemeTransition. ,
HorizontalOffset VerticalOffset.
,
, ,
.
. ,
.

.

<Grid>
<Button Content="Hello">
<Button.Transitions>
<TransitionCollection>
<ContentThemeTransition
HorizontalOffset="100" VerticalOffset="100"/>
</TransitionCollection>
</Button.Transitions>
</Button>
</Grid>

132

4. ,
, Transitions
, .
, ,
,
ChildrenTransitions.
( ).

<Grid>
<Grid.ChildrenTransitions>
<TransitionCollection>
<ContentThemeTransition
HorizontalOffset="100" VerticalOffset="100"/>
</TransitionCollection>
</Grid.ChildrenTransitions>
<Button Content="Hello">
</Button>
</Grid>
. ,
.

<Grid Background="White">
<Rectangle Height="100" Width="100" Fill="Red">
<Rectangle.Transitions>
<TransitionCollection>
<AddDeleteThemeTransition/>
</TransitionCollection>
</Rectangle.Transitions>
</Rectangle>
</Grid>
,
.
EntranceThemeAnimation
ContentThemeAnimation,
, .
EntranceTransitionAnimation .

133

Windows 8 C#
<Grid Background="White">
<Rectangle Height="100" Width="100" Fill="Red">
<Rectangle.Transitions>
<TransitionCollection>
<EntranceThemeTransition
FromHorizontalOffset="300"
FromVerticalOffset="300" />
</TransitionCollection>
</Rectangle.Transitions>
</Rectangle>
</Grid>
, XAML :
<Grid>
<StackPanel Name="stk">
<Rectangle Width="100" Height="100" Fill="Red"></Rectangle>
<Button Click="Button_Click">Click Me</Button>
</StackPanel>
</Grid>
:
private void Button_Click_3(object sender, RoutedEventArgs e)
{
Rectangle r = new Rectangle()
{ Height = 100, Width = 100,
Fill=new SolidColorBrush(Colors.Red) };
r.Transitions = new TransitionCollection();
r.Transitions.Add(new ReorderThemeTransition());
stk.Children.Insert(1, r);
}
, ,
StackPanel.
. ,
.
, :

134

4. ,
<Page.Resources>
<Style x:Key="DefaultButtonStyle" TargetType="Button">
<Setter Property="Transitions">
<Setter.Value>
<TransitionCollection>
<EntranceThemeTransition/>
</TransitionCollection>
</Setter.Value>
</Setter>
</Style>
</Page.Resources>
<StackPanel x:Name="LayoutRoot">
<Button Style="{StaticResource DefaultButtonStyle}"
Content="Transitioning Button" />
</StackPanel>
.


.
,
,
. .
DragItemThemeAnimation ,
.
DragOverThemeAnimation ,
.
DropTargetItemThemeAnimation
,
.
FadeInThemeAnimation
.
FadeOutThemeAnimation
.

135

Windows 8 C#
PopInThemeAnimation PopOutThemeAnimation
()
.
ComboBox.
RepositionThemeAnimation
, .
SplitCloseThemeAnimation SplitOpenThemeAnimation
(
),
,
.
TapDownThemeAnimation TapUpThemeAnimation
.

SwipeHintThemeAnimation
.
Windows,
(
).
SwipeBackThemeAnimation

.
, ,
.
. , ,
, ,
.
, .
<Grid Background="White">
<StackPanel>
<StackPanel.Resources>
<Storyboard x:Name="myStoryboard">
<FadeOutThemeAnimation
Storyboard.TargetName="myRectangle" />
</Storyboard>
</StackPanel.Resources>
<Rectangle PointerPressed="Rectangle_Tapped" x:Name="myRectangle"
Fill="Red" Width="100" Height="100" />
</StackPanel>
</Grid>
136

4. ,
, Storyboard.
. Storyboard
. .
, :

private void Rectangle_Tapped(object sender, PointerEventArgs e)


{
myStoryboard.Begin();
}
, , . ,
Storyboard, ,
.

137

5.

Windows 8 C#


, Binding.
, ,
Binding. Binding
, XAML.
, Binding XAML
. XAML ,
4. :
<Page x:Class="Chapter5_Binding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}"
VerticalAlignment="Center">
<StackPanel x:Name="LayoutRoot">
<Image Source="Assets/hydrangeas.jpg" Width="400">
<Image.Projection>
<PlaneProjection RotationY=
"{Binding Value, ElementName=slider}">
</PlaneProjection>
</Image.Projection>
</Image>
<Slider Minimum="0" Maximum="360" Name="slider"
Width="400" Margin="10"></Slider>
</StackPanel>
</Grid>
</Page>
Image,
Y.
PlaneProjection, RotationY,
Y.
, ,
. :
Path ,
. ,
Path ;
ElementName -;
140

5.
, Value
, RotationY .
-:
<Page x:Class="Chapter5_Binding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}"
VerticalAlignment="Center">
<StackPanel x:Name="LayoutRoot" >
<Image Source="Hydrangeas.jpg" Width="400">
<Image.Projection>
<PlaneProjection x:Name="projection"></PlaneProjection>
</Image.Projection>
</Image>
<Slider Minimum="0" Maximum="360" Name="slider"
Width="400" Margin="10"
Value=
"{Binding RotationY, ElementName=projection, Mode=TwoWay}">
</Slider>
</StackPanel>
</Grid>
</Page>
.
, , ,
Mode.
:
OneTime
,
. ;
OneWay
.
;
TwoWay
.
, .

141

Windows 8 C#
TwoWay Mode.
, , ,
.
. ,
,
, ,
Binding , .
,
.
<Page x:Class="Chapter5_Binding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006">
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}"
VerticalAlignment="Center">
<StackPanel x:Name="LayoutRoot">
<Image Source="Assets/hydrangeas.jpg" Width="400">
<Image.Projection>
<PlaneProjection x:Name="projection"></PlaneProjection>
</Image.Projection>
</Image>
<Slider Minimum="0" Maximum="360" Name="slider"
Width="400" Margin="10"
Value=
"{Binding RotationY, ElementName=projection, Mode=TwoWay}">
</Slider>
<TextBox Width="200" Text=
"{Binding RotationY, ElementName=projection,
Mode=TwoWay}"></TextBox>
</StackPanel>
</Grid>
</Page>
, ,
TextBox, TextBox.
, .
, ().
, TextBox ,
, . TextBox
.
142

5.
, ,
. TextBox
:
Binding binding = new Binding();
binding.ElementName = "projection";
binding.Path = new PropertyPath("RotationY");
binding.Mode = BindingMode.TwoWay;
txtBox.SetBinding(TextBox.TextProperty, binding);
,
.



, .
.
, :
public class Employee
{
public string FirstName
{
get;
set;
}
public string LastName
{
get;
set;
}
public string EMail
{
get;
set;
}

public int Age


{
get;
set;
}
143

Windows 8 C#
4 public.
: ,
, .

Employee, (
):

<Page x:Class=" Chapter5_Binding.MainPage "


xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="using:Element_Binding_Sample">
<Page.Resources>
<local:Employee x:Key="employee" Age="27" FirstName="Sergii"
LastName="Lutai" EMail="sergii.lutai@dct.ua" />
</Page.Resources>
<Grid x:Name="LayoutRoot" Width="400">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="First Name:" Grid.Row="0" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding FirstName, Source={StaticResource
employee}, Mode=TwoWay}"
Grid.Row="0" Grid.Column="1">
</TextBox>
<TextBlock Text="Last Name:" Grid.Row="1" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding LastName, Source={StaticResource
employee}, Mode=TwoWay}"
Grid.Row="1" Grid.Column="1">
</TextBox>
<TextBlock Text="EMail:" Grid.Row="2" Grid.Column="0">
</TextBlock>
144

5.
<TextBox Text="{Binding EMail, Source={StaticResource
employee}, Mode=TwoWay}"
Grid.Row="2" Grid.Column="1">
</TextBox>
<TextBlock Text="Age:" Grid.Row="3" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding Age, Source={StaticResource
employee}, Mode=TwoWay}"
Grid.Row="3" Grid.Column="1">
</TextBox>
</Grid>
</Page>
, , .
ElementName Source,
( ).
, DataContext:
<Page
x:Class="Chapter5_Binding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="using:Element_Binding_Sample">
<Page.Resources>
<local:Employee x:Key="employee" Age="27" FirstName="Sergii"
LastName="Lutai" EMail="sergii.lutai@dct.ua" />
</Page.Resources>
<Grid x:Name="LayoutRoot" Width="400" DataContext="{StaticResource
employee}">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
145

Windows 8 C#
</Grid.ColumnDefinitions>
<TextBlock Text="First Name:" Grid.Row="0" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding FirstName, Mode=TwoWay}"
Grid.Row="0" Grid.Column="1">
</TextBox>
<TextBlock Text="Last Name:" Grid.Row="1" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding LastName, Mode=TwoWay}" Grid.Row="1"
Grid.Column="1">
</TextBox>
<TextBlock Text="EMail:" Grid.Row="2" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding EMail, Mode=TwoWay}" Grid.Row="2"
Grid.Column="1">
</TextBox>
<TextBlock Text="Age:" Grid.Row="3" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding Age, Mode=TwoWay}"
Grid.Row="3" Grid.Column="1">
</TextBox>
</Grid>
</Page>
, . ,
,
DataContext , .
DataContext .
. DataContext ,
Employee public.
public.
, , .
, Employee
, , .
, DataContext XAML ,
Loaded:

146

5.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
Employee emp = new Employee();
emp.FirstName = "Sergii";
emp.LastName = "Lutai";
emp.EMail = "sergii.lutai@dct.ua";
emp.Age = 27;
LayoutRoot.DataContext = emp;
emp.FirstName = "Alex";
}
Employee, ,
. , ,
. ,
.
,
.
,

INotifyPropertyChanged.

,
.
. Employee,
INotifyPropertyChanged:

public class Employee: INotifyPropertyChanged


{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
PropertyChanged(this, e);
}
private
private
private
private

string firstName;
string lastName;
int age;
string email;

147

Windows 8 C#
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
OnPropertyChanged(new PropertyChangedEventArgs("FirstName"));
}
}
public string LastName
{
get { return lastName; }
set
{
lastName = value;
OnPropertyChanged(new PropertyChangedEventArgs("LastName"));
}
}
public string EMail
{
get { return email; }
set
{
email = value;
OnPropertyChanged(new PropertyChangedEventArgs("EMail"));
}
}
public int Age
{
get { return age; }
set
{
age = value;
OnPropertyChanged(new PropertyChangedEventArgs("Age"));
}
}
}
, .

148

5.


.
.
Employee, ToString:

public override string ToString()


{
return String.Format("{0} {1}", firstName, lastName);
}

Employee.
, ,
ItemsControl.
ListBox, .
, ,
. :
ItemsSource .
DisplayMemberPath,
ToString. ToString;
ItemTemplate
;
DisplayMemberPath
.
. ,
ListBox:
<Page x:Class="Chapter5_Binding.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:data="using:Chapter5_Binding">
<StackPanel>
<ListBox Height="300" Name="lstEmp"></ListBox>
<Grid x:Name="LayoutRoot" Background="White" Width="400"
DataContext="{Binding SelectedItem, ElementName=lstEmp}">
149

Windows 8 C#
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Text="First Name:" Grid.Row="0" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding Path=FirstName}" Grid.Row="0"
Grid.Column="1">
</TextBox>
<TextBlock Text="Last Name:" Grid.Row="1" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding Path=LastName}" Grid.Row="1"
Grid.Column="1">
</TextBox>
<TextBlock Text="EMail:" Grid.Row="2" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding Path=EMail}" Grid.Row="2"
Grid.Column="1">
</TextBox>
<TextBlock Text="Age:" Grid.Row="3" Grid.Column="0">
</TextBlock>
<TextBox Text="{Binding Path=Age}" Grid.Row="3"
Grid.Column="1">
</TextBox>
</Grid>
</StackPanel>
</Page>
,
ListBox, .

150

5.
, .
,
IEnumerable.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
List<Employee> employeeList = new List<Employee>();
Employee emp = new Employee();
emp.FirstName = "Sergiy";
emp.LastName = "Baydachnyy";
emp.EMail = "sbaidachni@gmail.com";
emp.Age = 31;
employeeList.Add(emp);
emp = new Employee();
emp.FirstName = "Sergii";
emp.LastName = "Lutai";
emp.EMail = "sergii.lutai@dct.ua";
emp.Age = 27;
employeeList.Add(emp);
lstEmp.ItemsSource = employeeList;
}
, ListBox,
!
:

151

Windows 8 C#

. 5.1.

, , , ListBox
. , ListBox
, . ,
LastName, OnPropertyChange,
ListBox , ToString
( ).
, DisplayMemberPath,
. ,
, .
. ListBox
, ItemTemplate.
ListBox:

152

5.
<ListBox Height="300" Width="400" Name="lstEmp">
<ListBox.ItemTemplate>
<DataTemplate>
<Border Background="Gray" BorderThickness="2"
CornerRadius="10" Width="396" Height="30">
<StackPanel Orientation="Horizontal" Margin="5">
<TextBlock Text="{Binding FirstName}"></TextBlock>
<TextBlock Text=" "></TextBlock>
<TextBlock Text="{Binding LastName}"></TextBlock>
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
,
.
, List
ObservableCollection. ,
,
INotifyCollectionChanged. ObservableCollection
.



. ,
ToString
.
, Employee
Salary.
private double salary;
public double Salary
{
get
{
return salary;
}
153

Windows 8 C#
set
{
salary = value;
OnPropertyChanged(new PropertyChangedEventArgs("Salary"));
}
}
,
. ,
, . ,
Silverlight . ,
IValueConverter, :
Convert ConvertBack.
, .
,
double .
public class MoneyConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
return ((double)value).ToString("C");
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
double result;
try
{
result = double.Parse((string)value,
NumberStyles.AllowThousands |
NumberStyles.AllowDecimalPoint |
NumberStyles.AllowCurrencySymbol);
}
catch
{
result = 0;
}
return result;
}
}
154

5.
,
Converter Binding.
, .
:

<UserControl.Resources>
<data:MoneyConverter x:Key="mConverter"></data:MoneyConverter>
</UserControl.Resources>
data ,
C#.

xmlns:data="clr-namespace:Chapter5_Binding"
Salary
:

<TextBlock Text="Salary:" Grid.Row="4" Grid.Column="0"></TextBlock>


<TextBox Text="{Binding Path=Salary,
Converter={StaticResource mConverter},
Mode=TwoWay}"
Grid.Row="4" Grid.Column="1">
</TextBox>

155

Windows 8 C#
:

. 5.2.

MVVM

MVVM .
2005 .
MVP
, .

,
. ,
, .
,
. MVC/MVP
.

156

5.
MVVM (. 5.3):
Model ,
;
View ;
ViewModel View,
Model, .
Model, View,
, View,
Model.

. 5.3.

157

Windows 8 C#
ViewModel:
public class ViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
, ViewModel
. ViewModel .
, Employee ViewModel
( , ViewModel Model
ViewModel !)
public class EmployeeViewModel : ViewModel
{
public ObservableCollection<Employee>
EmployeeCollection { get; private set; }
public ICommand AddEmployee { get; private set; }
public ICommand EditEmployee { get; private set; }
public ICommand DeleteEmplyee { get; private set; }
public EmployeeViewModel()
{
EmployeeCollection = new ObservableCollection<Employee>
{
new Employee { FirstName="Sergii", LastName="Lutai",
Age=27, EMail="sergii.lutai@dct.ua"},
new Employee { FirstName="Sergiy", LastName="Baydachnyy",
Age=32, EMail="Sergiy.Baydachnyy@microsoft.com"},
new Employee { FirstName="Ivan", LastName="Ivanov",
Age=29, EMail="ivan@ivanov.ua"}
};
158

5.
AddEmployee = new RelayCommand<Employee>
(this.AddEmployeeExecute, this.AddEmployeeCanExecute);
}
private void AddEmployeeExecute(Employee employee)
{
//TODO:
}
private bool AddEmployeeCanExecute(Employee employee)
{
//TODO:
return employee != null;
}

}
RelayCommand
System.Windows.Input.RelayCommand:
public class RelayCommand<T>: ICommand
{
private Action<T> action;
private Func<T, bool> func;
public RelayCommand(Action<T> action)
{
this.action = action;
}
public RelayCommand(Action<T> action, Func<T, bool> func)
{
this.action = action;
this.func = func;
}
public bool CanExecute(object parameter)
{
bool result = true;
T value = default(T);
if (parameter != null && !(parameter is T))
{
159

Windows 8 C#

parameter");

throw new ArgumentException(Wrong parameter type.",


}
if (parameter != null)
{
value = (T)parameter;
}

if (func != null)
{
result = func(value);
}
return result;

public event EventHandler CanExecuteChanged;


public void Execute(object parameter)
{
T value = default(T);

parameter");

if (parameter != null && !(parameter is T))


{
throw new ArgumentException(Wrong parameter type.",
}
if (parameter != null)
{
value = (T)parameter;
}

}
160

var canExecute = CanExecute(value);


if (canExecute)
{
action(value);
}

public void RaiseCanExecuteChanged()


{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}

5.
:
<Page
x:Class="MVVM.Sample.BlankPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MVVM.Sample"
xmlns:viewModel="using:ViewModel">
<Page.Resources>
<viewModel:EmployeeViewModel x:Key="EmployeeViewModel"/>
</Page.Resources>
<Page.DataContext>
<Binding Source="{StaticResource EmployeeViewModel}"/>
</Page.DataContext>
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<Button Content="Add New Employee" VerticalAlignment="Top"
Command="{Binding AddEmployee, Mode=OneTime,
Source={StaticResource EmployeeViewModel}}"/>
<ListBox ItemsSource="{Binding EmployeeCollection}"
Margin="0,40,0,0">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Button Content="Delete"
Command="{Binding DeleteEmplyee, Mode=OneWay,
Source={StaticResource EmployeeViewModel}}"
CommandParameter="{Binding Mode=OneWay}"/>
<Button Content="Edit"
Command="{Binding EditEmployee, Mode=OneWay,
Source={StaticResource EmployeeViewModel}}"
CommandParameter="{Binding Mode=OneWay}"/>
<TextBlock Text="{Binding FirstName}"
Margin="40,0,40,0"/>
<TextBlock Text="{Binding LastName}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Page>

161

Windows 8 C#
:

. 5.4.

. 5.5.
, MVVM,
.
- .
- .
12.
162

6.


Metro

Windows 8 C#
,

.
,
, .
Windows 8,
(Tile, Toast), ,

.
Windows 8.


Metro
.
. ,
, ,
. Windows 8
.

(. 6.1). ,
:

, . - ,
,
;

, ,
.
,
.
,
.

164

6. Metro

. 6.1.
XML,
. ,
, , ,
(. 6.2).
. .
, :
.

. 6.2.
5
. ,
,
. Windows
, .
,
.
,
.
; .
.
.
.

165

Windows 8 C#
,
, . ,
.

. ,
.
:
.png .jpg;
150 x 150 ;
310 x 150 ( );
30 30 .
;
150 KB.

(. 6.3).

. 6.3.
, .
, .
. Windows
8 30 .
, GetTemplateContent
Windows.UI.Notifications.TileUpdateManager. ,
Tile Message
( ):
166

6. Metro
XmlDocument tileXml = TileUpdateManager.
GetTemplateContent(TileTemplateType.TileWideText04);
XmlNodeList textElements = tileXml.GetElementsByTagName("text");
textElements.Item(0).AppendChild(tileXml.CreateTextNode("Tile Message"));
TileNotification tile = new TileNotification(tileXml);
TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);
GetTemplateContent ,
. xml. ,
:
<?xml version="1.0" encoding="utf-16"?><tile>
<visual lang="en-US">
<binding template="TileWideText04">
<text id="1"></text>
</binding>
</visual>
</tile>

:
<?xml version="1.0" encoding="utf-16"?><tile>
<visual lang="en-US">
<binding template="TileWideText04">
<text id="1">Tile Message</text>
</binding>
</visual>
</tile>

.

.
MSDN (http://msdn.microsoft.com/en-us/library/windows/
apps/windows.ui.notifications.tiletemplatetype.aspx).

( ), ,
.
.
167

Windows 8 C#
.

Windows 8,
, .
,
. ,
.

.
, .
:

;

RSS Reader;
..
,
,
.
:
RSS;
;
;
.

.
:
150 150 ;
;
310 150 ;
;
,
;
.
, :

;

;
168

6. Metro

.
Windows.
UI.StartScreen.SecondaryTile :
var secondaryTile = new Windows.UI.StartScreen.SecondaryTile();
secondaryTile.TileId = "3gFDG34GFS456FER";
secondaryTile.ShortName = "2nd Tile";
secondaryTile.DisplayName = "Secondary Tile";
secondaryTile.Arguments = "Some arguments";
secondaryTile.Logo = new Uri("ms-resource:Assets/secondLogo.png");
secondaryTile.WideLogo = new Uri("ms-resource:Assets/secondWideLogo.png");
SecondaryTile
:
TileId .
.
FindAllAsync SecondaryTile
, UpdateAsync ;
ShortName ,
;
DisplayName ,
,
;
Arguments ,
;
Logo ;
WideLogo .
WideLogo ,
.

RequestCreateAsync SecondaryTile:
secondaryTile.RequestCreateAsync();
Point,
(. 6.4)
.
RequestCreateForSelectionAsync,
.
169

Windows 8 C#

. 6.4.
, ,
:
secondaryTile.BackgroundColor = "Yellow";
secondaryTile.ForegroundText =
Windows.UI.StartScreen.ForegroundText.Dark;
secondaryTile.TileOptions =
Windows.UI.StartScreen.TileOptions.ShowNameOnLogo;
secondaryTile.SmallLogo = new Uri("ms-resource:Assets/secondSmallLogo.png");
BackgroundColor ;
ForegroundText ;
TileOptions
;

SmallLogo 30 x 30 .
.
,
. ,
.

. , /

(. 6.5) .
,
, .
170

6. Metro
/
.
.

. 6.5.

. ,

.

.


,
. ,
. .
0 99, .

:
none;
activity;
alert;
available;
away;
busy;
newMessage;
paused;
playing;
unavailable;
error.
171

Windows 8 C#

xml, .
:
var xmlDocument = Windows.UI.Notifications.BadgeUpdateManager.
GetTemplateContent(Windows.UI.Notifications.BadgeTemplateType.BadgeGlyph);
var xmlNodeList = xmlDocument.GetElementsByTagName("badge");
foreach (XmlElement xmlElement in xmlNodeList)
{
xmlElement.SetAttribute("value", "activity");
}
var badgeUpdater = Windows.UI.Notifications.BadgeUpdateManager.
CreateBadgeUpdaterForApplication();
badgeUpdater.Update(new Windows.UI.Notifications.BadgeNotification(xmlDocument));

GetTemplateContent

Windows.UI.Notifications.
BadgeUpdateManager .
Windows.UI.Notifications.BadgeTemplateType ,
. BadgeGlyph , ,
BadgeNumber .
xml CreateBadgeUpdaterForApplication
Windows.UI.Notifications.BadgeUpdateManager
BadgeUpdater, , ,
.
, .
StartPeriodicUpdate BadgeUpdater
Update.


,
.

.
, .
.

(. 6.6).

172

6. Metro

. 6.6.
.
, , .
Windows,
.
, ,
. ,
, .
.
.
T ,
. , ,
.
, .

. XML ,
, .
,
.
173

Windows 8 C#
:
.
7 .
.
,
;

(30 ) .

( ).

. ,
GetTemplateContent Windows.UI.Notifications.
ToastNotificationManager
Windows.UI.Notifications.ToastTemplateType:
ToastImageAndText01
, 3 ;
ToastImageAndText02
;
;
ToastImageAndText03
,
;
ToastImageAndText04
,
;
ToastText01
, 3 ;
ToastText02
,
;
ToastText03
,
;
ToastText04
,
.

174

6. Metro

:
var xmlDocument = Windows.UI.Notifications.ToastNotificationManager.
GetTemplateContent(Windows.UI.Notifications.ToastTemplateType.
ToastImageAndText03);
XmlNodeList toastTextAttributes = xmlDocument.GetElementsByTagName("text");
foreach (IXmlNode toastTextAttr in toastTextAttributes)
{
toastTextAttr.InnerText = "This is a toast notification!";
}
XmlNodeList toastImageAttributes = xmlDocument.GetElementsByTagName("image");
((XmlElement)toastImageAttributes[0]).SetAttribute("src",
"ms-resource:Assets/ToastImage.png");
((XmlElement)toastImageAttributes[0]).SetAttribute("alt",
"Apps Toast Notification");
var toastNotification = new Windows.UI.Notifications.
ToastNotification(xmlDocument);
var toastNotifier = Windows.UI.Notifications.
ToastNotificationManager.CreateToastNotifier();
toastNotifier.Show(toastNotification);

ToastNotification. ExpirationTime
. ,
:
Activated ;
Dismissed
;

Failed .
Show ToastNotifier
. (. 6.7).

175

Windows 8 C#

. 6.7.
xml :
<toast>
<visual lang="en-US">
<binding ...>
<image .../>
<text ...></text>
</binding>
</visual>
<audio scr="ms-winsoundevent:..." loop="True|False"
silent="True|False" />
</toast>
audio
. scr ,
.
:
Notification.IM,Notification.Looping.Call,
Notification.Looping.
Alarm. loop true ,

,
silent
/
.
.

, ,
.
.
176

6. Metro

, ,
ToastNotification ScheduledToastNotification
AddToSchedule ToastNotifier.

Push
,
.
. ,
.
push-,
, ,
, . Push-
, .
push-
Windows Push Notification Services (WNS) .
WindowsLive
Application Management (https://manage.dev.live.com/build).
LiveId.
,
. .

:
Package Security Identifier (SID)
PackageSID,
WNS,
. clientid
OAuth ;
Secret Key client_seret OAuth .
. ,
Package SID Secret Key,
.
,
WNS.
, WNS
(. 6.8):

177

Windows 8 C#

. 6.8.
1. Notification Client Platform
push-;
2. Notification Client Platform WNS.
URI;
3. push- ;
4. URI .
;
5. , WNS,
URI. POST
.
https. ;
6. WNS
.
CreatePushNotificationChannelForApplicationAsync
Windows.Networking.PushNotifications.PushNotificationChannelManager
WNS
PushNotificationChannel .
,
.
178

6. Metro
OnPushNotificationReceived.
,
.
void OnPushNotificationReceived(PushNotificationChannel sender,
PushNotificationReceivedEventArgs e)
{
string typeString = String.Empty;
string notificationContent = String.Empty;
switch (e.NotificationType)
{
case PushNotificationType.Badge:
typeString = "Badge";
notificationContent = e.BadgeNotification.
Content.GetXml();
break;
case PushNotificationType.Tile:
notificationContent = e.TileNotification.
Content.GetXml();
typeString = "Tile";
break;
case PushNotificationType.Toast:
notificationContent = e.ToastNotification.
Content.GetXml();
typeString = "Toast";
break;
}
//
e.Cancel = true;
}
Push-
, .
.
, WNS
5 ,
, ,
.

179

Windows 8 C#


Windows 8
.
Windows 8 Metro.

. , Windows 8
. ,
,
. ,
.
, .
,
.
:
Settings
Search;
Sharing;
Play To;
App to App Picking.
.
.

(Settings)

(. 6.9).

180

6. Metro

. 6.9.
,
.
Show() Windows.UI.ApplicationSettings.SettingsPane.


:

181

Windows 8 C#
var settingsPane = Windows.UI.ApplicationSettings.SettingsPane
.GetForCurrentView();
settingsPane.CommandsRequested += settingsPane_CommandsRequested;
..........
void settingsPane_CommandsRequested(SettingsPane sender,
SettingsPaneCommandsRequestedEventArgs args)
{
args.Request.ApplicationCommands.Add(new
SettingsCommand("SomeId", "Log Out", (handler)=>
{
//TODO:
}));
}
GetForCurrentView SettingsPane, ,
, CommandsRequested

.
SettingsCommand
, ,
.
, , ,
.



. ,
Windows 8,
. ,

.
, ,
.
,
(. 6.10).

182

6. Metro

. 6.10.
Windows.
ApplicationModel.Search.SearchPane. ,
GetForCurrentView() .
:
QuerySubmitted ,
;
SuggestionsRequested
;
VisibilityChanged / .

183

Windows 8 C#

(Sharing)

.

,
.
:
,
;
, .
,
/.
Windows.
ApplicationModel.DataTransfer.DataTransferManager.
, GetForCurrentView() :
datatransferManager = DataTransferManager.GetForCurrentView();
datatransferManager.DataRequested += new TypedEventHandler
<DataTransferManager, DataRequestedEventArgs>(this.DataRequested);
DataRequested ,
. :
void DataRequested(DataTransferManager sender, DataRequestedEventArgs e)
{
e.Request.Data.Properties.Title = this.dataPackageTitle;
e.Request.Data.Properties.Description =
this.dataPackageDescription;
if (this.dataPackageThumbnail != null)
{
e.Request.Data.Properties.Thumbnail =
this.dataPackageThumbnail;
}
e.Request.Data.SetText(this.dataPackageText);
}
Properties
.
184

6. Metro
, ,
OnShareTargetActivated Application
:

protected override async void OnShareTargetActivated


(ShareTargetActivatedEventArgs args)
{
if (args.Kind == Windows.ApplicationModel.
Activation.ActivationKind.ShareTarget)
{
var text = await args.ShareOperation.Data.
GetTextAsync()
}
}
, , ,
html .
. , -
.

185

7.

Windows 8 C#
Metro-
,
. Windows 8

. ,

, TCP UDC
.


,
,
Windows 8.
.Net Framework
. Windows 8
.
.

async await. async ,
- . await
.
,
await.
await
.
async . ,
- . await
.
,
. await
. , (,
)
.
:

188

7.
private async Task<byte[]> GetURLContentsAsync(string url)
{
. . .
using (WebResponse webResponse =
await webRequest.GetResponseAsync())
. . .
}

MSDN (http://msdn.microsoft.com/en-us/library/hh191443(v=vs.110).aspx).


Connectivity API, Windows
Runtime, Metro-

.
-
GetInternetConnectionProfile Windows.Networking.
Connectivity. NetworkInformation. ConnectionProfile
. ,
, . 7.1.

. 7.1.
189

Windows 8 C#
:
Var connectionProfile = Windows.Networking.Connectivity.
NetworkInformation.GetInternetConnectionProfile()
connectionProfileInfo = "Profile Name : " +
connectionProfile.ProfileName + "\n";
switch (connectionProfile.GetNetworkConnectivityLevel())
{
case NetworkConnectivityLevel.None:
connectionProfileInfo += "Connectivity Level : None\n";
break;
case NetworkConnectivityLevel.LocalAccess:
connectionProfileInfo += "Connectivity Level :
Local Access\n";
break;
case NetworkConnectivityLevel.ConstrainedInternetAccess:
connectionProfileInfo += "Connectivity Level :
Constrained Internet Access\n";
break;
case NetworkConnectivityLevel.InternetAccess:
connectionProfileInfo += "Connectivity Level :
Internet Access\n";
break;
}
switch (connectionCost.NetworkCostType)
{
case NetworkCostType.Unrestricted:
connectionProfileInfo += "Cost: Unrestricted";
break;
case NetworkCostType.Fixed:
connectionProfileInfo += "Cost: Fixed";
break;
case NetworkCostType.Variable:
connectionProfileInfo += "Cost: Variable";
break;
case NetworkCostType.Unknown:
connectionProfileInfo += "Cost: Unknown";
break;
default:
connectionProfileInfo += "Cost: Error";
break;
}
190

7.
connectionProfileInfo += "\n";
connectionProfileInfo += "Roaming: " + connectionCost.Roaming + "\n";
connectionProfileInfo += "Over Data Limit: " + connectionCost.
OverDataLimit + "\n";
connectionProfileInfo += "Approaching Data Limit : " +
connectionCost.ApproachingDataLimit + "\n";
, ConnectionProfile,
, .
DataUsage, GetLocalUsage
ConnectionProfile (. 7.2).

. 7.2.
-

. ,
WiFi,
.


,
,
. Metro-
, Windows 8
.

.Net Framework : HttpClient ( WebClient)
HttpWebRequest/HttpWebResponse. ,
,
. ,
?
!
.
Windows.Networking.
BackgroundTransfer.BackgroundDownloader (
191

Windows 8 C#
) Windows.Networking.BackgroundTransfer.BackgroundUploader
( ).
, , :
DownloadOperation download = null;
try
{
Uri source = new Uri(serverAddressFile);
StorageFile destinationFile = await KnownFolders.
PicturesLibrary.CreateFileAsync("Image.jpg",
CreationCollisionOption.GenerateUniqueName);
BackgroundDownloader downloader = new BackgroundDownloader();
download = downloader.CreateDownload(source, destinationFile);
//
HandleDownloadAsync(download, true);
}
catch (Exception ex)
{
. . .
}
. . . . . . . . .
private List<DownloadOperation> activeDownloads;
private async void HandleDownloadAsync(DownloadOperation
download, bool start)
{
try
{
activeDownloads.Add(download); //
.
Progress<DownloadOperation> progressCallback =
new Progress<DownloadOperation>(DownloadProgress);
if (start)
{
// .
await download.StartAsync().AsTask(cts.Token,
progressCallback);
192

7.
}
else
{
// ,
, .
await download.AttachAsync().AsTask(cts.Token,
progressCallback);
}
}
catch (TaskCanceledException)
{
. . . . .
}
catch (Exception ex)
{
. . . . .
}
finally
{
activeDownloads.Remove(download);
}
}

DownloadOperation.
. , ,
,
. CreateDownload
BackgroundDownloader. :
( source ) ,
( destinationFile ).
StartAsync, . AttachAsync
.
AsTask .

(. 7.3).

193

Windows 8 C#

. 7.3.

RSS
RSS-
.
/
. RSS XML-
().
, RSS, ,
.
Metro-
Microsoft .
Windows.Web.Syndication.
RSS- SyndicationClient
. :

194

7.
SyndicationClient client = new SyndicationClient();
client.BypassCacheOnRetrieve = true;
// user-agent
client.SetRequestHeader("user-agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64;
Trident/6.0)");
SyndicationFeed currentFeed = await client.RetrieveFeedAsync(uri);
BypassCacheOnRetrieve true,
.
user-agent, .
currentFeed ,
.
Items:
foreach (var item in currentFeed.Items)
{
//
string title = item.Title != null ? item.Title.Text : "(no title)";
//
string link = string.Empty;
if (item.Links.Count > 0)
{
link = item.Links[0].Uri.AbsoluteUri;
}
//
string content = "(no content)";
if (item.Content != null)
{
content = item.Content.Text;
}
else if (item.Summary != null)
{
content = item.Summary.Text;
}
}

195

Windows 8 C#

WebAuthenticationBroker

.
- , LiveId . ,

OAuth. , -
,
.
, .

.

WebAuthenticationBroker,
Windows.Security.Authentication.Web.
OAuth OpenID,
(,
) .
:
1. , .
2. SID .
3. , . . ,
.

Facebook :
//
private static string FACEBOOK_DATA_LINK =
"https://graph.facebook.com/me?access_token=";
private static string FACEBOOK_URI =
"https://www.facebook.com/dialog/oauth";
private static string FACEBOOK_REDIRECT_URI =
"https://www.facebook.com/connect/login_success.html";
private static string CLIENT_ID =
"< Facebook >";
private static string CLIENT_SECRET_KEY =
"< Facebook >";
private static string RESPONSE_TYPE = "token";
private static string TOKEN_PATTERN =
string.Format("{0}#access_token={1}&expires_in={2}",
FACEBOOK_REDIRECT_URI, "(?<access_token>.+)", "(?<expires_in>.+)");
196

7.
. . . . . . . . . .
var requestUri = new Uri(string.Format("{0}?client_id=
{1}&redirect_uri={2}&response_type={3}&display=popup&scope=
publish_stream&client_secret={4}&scope=publish_stream,
user_photos,user_location,offline_access",
FACEBOOK_URI, CLIENT_ID, FACEBOOK_REDIRECT_URI,
RESPONSE_TYPE, CLIENT_SECRET_KEY), UriKind.RelativeOrAbsolute);
var callbackUri = new Uri(FACEBOOK_REDIRECT_URI,
UriKind.RelativeOrAbsolute);
var auth = await WebAuthenticationBroker.AuthenticateAsync
( WebAuthenticationOptions.None, requestUri, callbackUri);
switch (auth.ResponseStatus)
{
case WebAuthenticationStatus.ErrorHttp:
// ,
break;
case WebAuthenticationStatus.Success:
var match = Regex.Match(auth.ResponseData, TOKEN_PATTERN);
var access_token = match.Groups["access_token"].Value;
var expires_in = match.Groups["expires_in"].Value;
break;
case WebAuthenticationStatus.UserCancel:
//
break;
default:
break;
}
WebAuthenticationBroker . 7.4.

197

Windows 8 C#

. 7.4.

, Windows 8

,
. ,
- ,
, TCP/UDP- .
, , .
MSDN (http://msdn.microsoft.com/en-us/library/windows/apps/hh452751.aspx).

198

8.

Windows 8 C#



. Windows Runtime
. , XAML
, .
, AppBarButtonStyle
BackButtonStyle, Button
( Back). Button
, ,
,
.

. , ,
, .
,
, (, ).

(AppBarButtonStyle). , ,
:

<Setter Property="Foreground"
Value="{StaticResource AppBarItemForegroundBrush}"/>
<Setter Property="VerticalAlignment" Value="Stretch"/>
<Setter Property="FontFamily" Value="Segoe UI Symbol"/>
<Setter Property="FontWeight" Value="Normal"/>
. ,
Template.
.
,
- ControlTemplate,
.
ControlTemplate ( ),
TargetType,
.

200

8.
ControlTemplate ,
.
,
ControlTemplate .
Grid.
, , ,
. ,
: ,
(
), ,
.
, , ControlTemplate,
,
. ,
Expression Blend 5, .
,

.
, Expression Blend 5,
.
,
Edit Template -> Edit a Copy:

. 8.1.

201

Windows 8 C#

.

( ).

. 8.2.
,
. ,
Blend , Template.

.
, ,
.
, .
,
Parts (). ,
TemplatePart:

[TemplatePart(Name = "TextElement", Type = typeof(TextBlock))]


[TemplatePart(Name = "UpButtonElement", Type = typeof(RepeatButton))]
[TemplatePart(Name = "DownButtonElement", Type = typeof(RepeatButton))]
public class MyControl: Control
,
:
RepeatButton. ,

, .
202

8.


, ,
. ,
.
, :
;
;
XAML;

.

,
TemplateVisualState.
Button :

[TemplateVisualState(Name = "Normal", GroupName = "CommonStates")]


[TemplateVisualState(Name = "PointerOver", GroupName = "CommonStates")]
[TemplateVisualState(Name = "Pressed", GroupName = "CommonStates")]
[TemplateVisualState(Name = "Disabled", GroupName = "CommonStates")]
[TemplateVisualState(Name = "Unfocused", GroupName = "FocusStates")]
[TemplateVisualState(Name = "Focused", GroupName = "FocusStates")]
[TemplateVisualState(Name = "PointerFocused", GroupName = "FocusStates")]
public class Button : ButtonBase
{
}
,
: . ,
. ,
,
.
,

GoToState VisualStateManager:

203

Windows 8 C#
private void UpdateStates(bool useTransitions)
{
if (isFocused)
{
VisualStateManager.GoToState(this, "Focused",
useTransitions);
}
else
{
VisualStateManager.GoToState(this, "Unfocused",
useTransitions);
}
}
,
.
GoToState
(Snapped, Filled . .).
XAML.
.
VisualStateManager,
(VisualState), (VisualStateGroup):

<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="PointerOver">
<Storyboard>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="BackgroundGlyph"
Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource
AppBarItemHoverBackgroundBrush}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames
Storyboard.TargetName="Content"
Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0"
204

8.
Value="{StaticResource
AppBarItemHoverForegroundBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="Pressed">
. . . . .
.
, .
, , KeyTime
Duration, 0. ,
. ,
VisualTransition,
StoryBoard.

<VisualTransition From="Normal" GeneratedDuration="0:0:3"


To="PointerOver"/>
, . , Expression
Blend ,
.
, States Parts, .
Parts ,

, ,
. States , ,

.

205

Windows 8 C#

. 8.3.

Expression Blend

XAML
Expression Blend. :
XAML
;
, Adobe
Photoshop Adobe Illustrator ( ,
);
206

8.
(
Visual Studio);
(,
.).
, Blend ,
, Visual Studio.
, , .
Expression Blend (,
Visual Studio, ,
), File -> New
Project, .
, C#, Blend
JavaScript/HTML.
, , JavaScript- :

. 8.4.
, Visual
Studio : HTML XAML. ,
XAML, C#, Visual Basic .NET C++.
207

Windows 8 C#
, , :

. 8.5.
, Projects,
. , ,
. ,
.

, (Selection).
Projects - Solution Explorer Visual Studio.
.
: ,
. . , .
, Visual Studio.

208

8.

. 8.6.
Projects Assets,
, ,
, .
.

. 8.7.
209

Windows 8 C#
Objects and Timeline
Silverlight-, .

. 8.8.
Objects and Timeline
,
, Properties. ,
.

. 8.9.
210

8.
, , XAML-
, View ->
Active Document View.


Expression Blend
. Objects and
Timeline, New
Create Storyboard Resource.

. 8.10.
Expression Blend Storyboard ,
, .
Storyboard .

211

Windows 8 C#

. 8.11.

. ,
.
, .
.
, .

. 8.12.

212

9.

Windows 8 C#

MediaElement

Silverlight Windows Presentation Foundation,
.
MediaElement ,
. Windows Runtime
, .
WinRT, Silverlight, MediaElement
. :
WMV1: Windows Media Video 7;
WMV2: Windows Media Video 8;
WMV3: Windows Media Video 9;
WMVA: Windows Media Video Advanced Profile, non-VC-1;
WVC1: Windows Media Video Advanced Profile, VC-1;
H.264;
3D (, Silverlight).
,
, Expression
Encoder.
, :
WAV;
WMA7: Windows Media Audio 7;
WMA8: Windows Media Audio 8;
WMA9: Windows Media Audio 9;
WMA10: Windows Media Audio 10;
MP3: ISO/MPEG-1 Layer 3;
AAC.
, , , MediaElement,
http, https mms. Windows Media
Service .
MediaElement , .
214

9.
http https,
, .
mms,
.
, MediaElement
.
MediaElement
FrameworkElement. , ,
.
. :
Source (),
MediaElement.
SetSource, ;
AutoPlay ,
.
true. ,
, false;
IsMuted , true;
Volume .
0 1. 0,5.

, Volume 1.
, ;
Balance -1 1.
0,
. -1,
, +1, ;
Position .
Position,
TimeSpan, ,
;
CanSeek ,
Position . MediaElement
, ;
CanPause ,
. , false;
CurrentState
MediaElementState: Buffering,
Opening, Playing, Closed, Paused, Stopped;
215

Windows 8 C#
DownloadProgress ,
. ,
;
DownloadProgressOffset (),
.
, ,
;
DroppedFramesPerSecond ,
- .
;
Markers , .
;
NaturalDuration -
.
TimeSpan;
NaturalVideoWidth , NaturalVideoHeight,
;
NaturalVideoHeight .
MediaElement:

<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">


<Grid x:Name="LayoutRoot" Background="Gray" Width="400" Height="400">
<MediaElement Source="WildLife.wmv"></MediaElement>
</Grid>
</Grid>

. , :

216

9.

. 9.1.
, ,
,
. MediaElement .
Clip.
, ,
.
MediaElement, ,
:
SetSource SetSource Source
;
Play .
, ;
Pause .
, ;
Stop .
217

Windows 8 C#
, , , , MediaElement.

. ,
:
BufferingProgressChanged
BufferingChanged,
;
CurrentStateChanged
;

DownloadProgressChanged
;
MarkerReached ,
, .
;
MediaEnded ,
;
MediaFailed ,
, , .
,
JavaScript, ;
MediaOpened ,
.
, , ,
MediaElement
. ,
, .
:
<StackPanel HorozontalAlignment="Left">
<MediaElement Name="myMedia" Height="300"
Source="WildLife.wmv"
Margin="5" AutoPlay="False"
MediaOpened="myMedia_MediaOpened"
MediaEnded="myMedia_MediaEnded">
</MediaElement>
<StackPanel Orientation="Horizontal">
<TextBlock Name="durationText"
Text="Duration: " Margin="5">
</TextBlock>

218

9.
<TextBlock
Text=
"{Binding Position.TotalSeconds,
ElementName=myMedia, Mode=OneWay}"
Margin="5">
</TextBlock>
<TextBlock Text="/" Margin="5"></TextBlock>
<TextBlock Text="" Name="secondsText" Margin="5">
</TextBlock>
</StackPanel>
<Slider Name="positionSlider" Minimum="0"
Margin="5" IsEnabled="False"
Value=
"{Binding Position.TotalSeconds,
ElementName=myMedia, Mode=OneWay}"
>
</Slider>
<StackPanel Orientation="Horizontal" >
<Button Content="Play" Name="playButton" Margin="5"
Width="100" IsEnabled="False"
Click="playButton_Click"></Button>
<Button Content="Pause" Name="pauseButton"
IsEnabled="False" Margin="5" Width="100"
Click="pauseButton_Click" ></Button>
<Button Content="Stop" Name="stopButton"
Margin="5" Width="100" IsEnabled="False"
Click="stopButton_Click" ></Button>
<CheckBox Content="Mute" Margin="5" IsEnabled="False"
Name="muteBox" IsChecked=
"{Binding IsMuted, ElementName=myMedia, Mode=TwoWay}"
>
</CheckBox>
</StackPanel>
<StackPanel Orientation="Horizontal" >
<TextBlock Text="Volume:" Margin="5"></TextBlock>
<Slider Name="volumeSlider" Minimum="0" Maximum="1"
Width="200" IsEnabled="False" StepFrequency="0.1"
Value=
"{Binding Volume, ElementName=myMedia, Mode=TwoWay}">
</Slider>
</StackPanel>
</StackPanel>

219

Windows 8 C#
,
, ,
.
:

. 9.2.

, - .
:

220

9.
private void myMedia_MediaOpened(object sender, RoutedEventArgs e)
{
positionSlider.IsEnabled = true;
volumeSlider.IsEnabled = true;
playButton.IsEnabled = true;
stopButton.IsEnabled = true;
positionSlider.Maximum =
myMedia.NaturalDuration.TimeSpan.TotalSeconds;
secondsText.Text =
myMedia.NaturalDuration.ToString();
}
private void playButton_Click(object sender, RoutedEventArgs e)
{
playButton.IsEnabled = false;
pauseButton.IsEnabled = true;
myMedia.Play();
}
private void pauseButton_Click(object sender, RoutedEventArgs e)
{
pauseButton.IsEnabled = false;
playButton.IsEnabled = true;
myMedia.Pause();
}
private void stopButton_Click(object sender, RoutedEventArgs e)
{
pauseButton.IsEnabled = false;
playButton.IsEnabled = true;
myMedia.Stop();
}
private void myMedia_MediaEnded(object sender, RoutedEventArgs e)
{
pauseButton.IsEnabled = false;
playButton.IsEnabled = true;
}

221

Windows 8 C#
(Stop,
Start, Pause) ,
.
, .
. ,
, ,
. .
.


,
. ()
Microsoft Expression Encoder (
), (
).
. ,
,
.
. ,
,
( MarkerReached)
. .
,
:
<StackPanel>
<MediaElement Width="400" Height="300" Name="myMedia"
Source="Wildlife.wmv" MediaOpened="myMedia_MediaOpened"
MarkerReached="myMedia_MarkerReached">
</MediaElement>
<TextBlock Text="" HorizontalAlignment="Center"
Name="subtitleText" FontSize="16" FontWeight="Bold" >
</TextBlock>
</StackPanel>
XML .
, Subtitle,
.
.
222

9.

, ,
. :
public sealed partial class BlankPage : Page
{
Subtitle[] subtitles = new Subtitle [3];
public BlankPage()
{
InitializeComponent();
Subtitle s=new Subtitle();
s.text = " ";
s.time = new TimeSpan(0, 0, 0);
subtitles[0] = s;
s = new Subtitle();
s.text = " ";
s.time = new TimeSpan(0, 0, 5);
subtitles[1] = s;
s = new Subtitle();
s.text = " ";
s.time = new TimeSpan(0, 0, 7);
subtitles[2] = s;
}
private void myMedia_MediaOpened(object sender, RoutedEventArgs e)
{
TimelineMarker t;
foreach (Subtitle s in subtitles)
{
t = new TimelineMarker();
t.Time = s.time;
t.Text = s.text;
myMedia.Markers.Add(t);
}
}
private void myMedia_MarkerReached(object sender,
TimelineMarkerRoutedEventArgs e)
{
223

Windows 8 C#
subtitleText.Text = e.Marker.Text;
}
}
class Subtitle
{
public TimeSpan time;
public String text;
}
.

. 9.3.
, . ,
.

224

9.

MediaPlayer
MediaElement ,
.
, MediaElement
. ,
MediaPlayer. ,
:
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<Grid x:Name="LayoutRoot" Background="Gray" Width="400" Height="400">
<MediaPlayer Source="WildLife.wmv" Name="md"></MediaPlayer>
</Grid>
</Grid>
,
, .

. 9.4.

225

Windows 8 C#


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

CameraCaptureUI
CameraCaptureUI,
.
. ,
, ,
Image, :
<Grid Background="{StaticResource ApplicationPageBackgroundBrush}">
<StackPanel Orientation="Vertical">
<Button Content="Take a Picture" Click="Button_Click_1" />
<Image Name="photo" Height="400" Width="400"></Image>
</StackPanel>
</Grid>
, ,
:
private async void TakeAPicture()
{
CameraCaptureUI camera=new CameraCaptureUI();
camera.PhotoSettings.Format = CameraCaptureUIPhotoFormat.Png;
camera.PhotoSettings.MaxResolution =
CameraCaptureUIMaxPhotoResolution.HighestAvailable;
StorageFile file = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
BitmapImage btn = new BitmapImage();
btn.SetSource(await file.OpenAsync(FileAccessMode.Read));

226

9.
photo.Source = btn;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
TakeAPicture();
}
CameraCaptureUI
. ,
, ,
.
, .
.
CaptureFileAsync.
(, , ) ,
, ,
.
, , , ,
:

. 9.5.

227

Windows 8 C#
,
() .
.
, -
( ):

. 9.6.
, (,
),
.
.
StorageFile,
(
). ,
BitmapImage Image,
Source.
, ,
:

228

9.

. 9.7.

229

Windows 8 C#

Media Capture API



Media Capture API. ,
MediaCapture.
()
.
, .
, MediaCapture
:
DeviceInformationCollection devices=
await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
MediaCapture media=new MediaCapture();
MediaCaptureInitializationSettings settings =
new MediaCaptureInitializationSettings();
settings.RealTimeModeEnabled = true;
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
settings.PhotoCaptureSource = PhotoCaptureSource.Auto;
settings.VideoDeviceId=devices[0].Id;
await media.InitializeAsync(settings);
MediaEncodingProfile profile =
MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);
,
,
MediaCapture.
MediaCaptureInitializationSettings, .
InitializeAsync.
, , ,
.
, , StartRecordToStreamAsync
StartRecordToStorageFileAsync:
media.StartRecordToStorageFileAsync(profile, file);
, ,
.
230

9.


MediaTranscoder,
.
,
,
. .
,
,
(
Full HD ).
, ,
,
StorageFile. MediaTranscoder
, .
, ,
, ,
.
:
.

MediaEncodingProfile ,
CreateMp4,
, . :
MediaEncodingProfile profile=
MediaEncodingProfile.CreateMp4(VideoEncodingQuality.HD720p);
. CreateFromFileAsync
CreateFromStreamAsync
. ,
;
. MediaEncodingProfile
,
.
,
.
MediaTrascoder : PrepareFileTranscodeAsync,
PrepareStreamTranscodeAsync.
, .

231

Windows 8 C#
, MediaTranscoder
, TrimStartTime TrimStopTime,
, .

PlayTo
DLNA (Digital Living Network Alliance) ,

(, , ).
DLNA, Windows 8
, , WiFi.
, , .
, DLNA ,
PlayTo.

, SourceRequested
. ,
.
, , ,
Windows Devices.
, DLNA ( ),
. ,
PlayTo .
, .
, PlayTo, :
PlayToManager,
GetForCurrentView;

SourceRequested;

SetSource
.
, . ,
,
. PlayTo
, .
,
PlayTo:

232

9.
private PlayToManager ptm;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ptm = PlayToManager.GetForCurrentView();
ptm.SourceRequested += SourceRequested;
}
private void SourceRequested(PlayToManager sender,
PlayToSourceRequestedEventArgs e)
{
PlayToSourceRequest sr = e.SourceRequest;
PlayToSource controller = null;
controller = ((MediaElement)mediaElement).PlayToSource;
sr.SetSource(controller);
}

233

10.

Windows 8 C#


,
.
.
, ,
, .
Windows Runtime .

, .

.

.
.


, :
.
, Metro
, .
Windows Runtime ,
,
.
. ,
, .
, ,
.
ApplicationDataContainer ,
,
ApplicationDataCompositeValue.
,
( ).
ApplicationDataCompositeValue
. ,
.
,
.

236

10.
Windows.Storage
. ,
,
.
ApplicationDataContainer current =
ApplicationData.Current.LocalSettings;
ApplicationDataContainer named =
current.CreateContainer(
"myContainer", ApplicationDataCreateDisposition.Always);
,
, .
, .
, : Boolean,
Double, Int32, Int64, Single, String, UInt8, UInt32, UInt64.
, -
.
current.Values["myValue"] = 5;
current.Containers["myContainer"].Values["mySecondValue"] = "Hello";
, ,
.
, ()
, .
ApplicationDataCompositeValue composite =
new ApplicationDataCompositeValue();
composite["firstVal"] = 1;
composite["secondVal"] = "Hello";
current.Values["compValue"] = composite;
.
,
StorageFolder.
StorageFolder current = ApplicationData.Current.LocalFolder;
237

Windows 8 C#
.
CreateFileAsync .
CreateFolderAsync .
DeleteAsync ( ).
RenameAsync .
GetFileAsync
( StorageFile).
GetFilesAsync , .
GetFolderAsync .
GetFoldersAsync ,
.
OpenStreamForReadAsync ,
Stream, .NET Framework
.
.NET .
OpenStreamForWriteAsync ,
.
OpenAsync
Windows Runtime,
.
,
.
public async void WriteFile()
{
StorageFolder current = ApplicationData.Current.LocalFolder;
StorageFile file = await current.CreateFileAsync(
"hello.txt", CreationCollisionOption.ReplaceExisting);
IRandomAccessStream writeStream =
await file.OpenAsync(FileAccessMode.ReadWrite);
IOutputStream outputStream = writeStream.GetOutputStreamAt(0);
DataWriter dataWriter = new DataWriter(outputStream);
dataWriter.WriteString("hello");
await dataWriter.StoreAsync();
outputStream.FlushAsync();
}
238

10.
,
await, async.
WinRT,
.NET, ,
DataWriter. ,
.
.
public async void ReadFile()
{
StorageFolder current = ApplicationData.Current.LocalFolder;
StorageFile sampleFile = await current.GetFileAsync("hello.txt");
IRandomAccessStream readStream =
await sampleFile.OpenAsync(FileAccessMode.Read);
IInputStream inputStream = readStream.GetInputStreamAt(0);
DataReader dataReader = new DataReader(inputStream);
string myString = dataReader.ReadString((uint)readStream.Size);
}


,
,
,
.
, ,
30 , .
,
. ,
. ,
,
, .
,
. . ,
:
ApplicationDataContainer current=ApplicationData.Current.RoamingSettings;
StorageFolder file=ApplicationData.Current.RoamingFolder;
239

Windows 8 C#
, ,
. , ApplicationData
, :
RoamingStorageQuota ,
;
RoamingStorageUsage .

,
.
, ,
.
, ,
,
.

void InitHandlers()
{
ApplicationData.Current.DataChanged +=
new TypedEventHandler<ApplicationData,
object>(DataChangeHandler);
}
void DataChangeHandler(ApplicationData appData, object o)
{
//
}


, .
.
. ,
.
, .
StorageFolder folder=ApplicationData.Current.TemporaryFolder;
.
240

10.



. ,
,
, . ,
,
My Pictures. Windows Runtime
, KnownFolders,
.
DocumentsLibrary My Documents.
PicturesLibrary My Pictures.
MusicLibrary My Music.
HomeGroup
.
MediaServerDevices ,

DLNA
( PlayTo).
RemovableDevices
, .

StorageFolder,
. StorageFolder,
.
, .
Windows, ,
,
( ).
, ,
() File Type
Associations. , .docx-,
,
. ,
.
,
.

.
FileOpenPicker, ,
.
241

Windows 8 C#
FIleOpenPicker ,
. .

public async void SelectFile()


{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation =
PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".tif");
StorageFile file=await openPicker.PickSingleFileAsync();
}
, ,
.tif.

. 10.1.
, ,
, FileSavePicker,
.

242

10.



, ,
Windows 8.
Metro ,
,
. ,
,
. c Windows 8
, -
, , .
, Windows 8
, , ,
. .
, ,
, .

, (
)
.
, .

(
), ,
.
, Application
. .
Activated
. , ,
,
. ,
.
Suspending
. 5 ,
.
,
.

243

Windows 8 C#
Resuming ,
, .
,
, . ,
,
, Dispatcher.
Activated. ,
: ;
- ;
FilePicker . , ,
Application .
OnFileActivated, OnSearchActivated, OnShareTargetActivated
. ,
- , ,
. ,
OnActivated, .
async protected override void OnActivated(IActivatedEventArgs args)
{
switch (args.Kind)
{
case ActivationKind.CameraSettings:
. . . .
break;
case ActivationKind.ContactPicker:
. . . .
break;
case ActivationKind.PrintTaskSettings:
. . . .
break;
. . . .
}
base.OnActivated(args);
}
,
OnLanched ( ) ,
, ,
.
OnLauched PreviousExecutionState,
, .
.
244

10.
ClosedByUser .
,
Suspending.
NotRunning ,
.
Running . ,
Suspending.
Suspended .
Terminated ,
.
, ,
- .

245

11.

Windows 8 C#



, , .
, ,
.
.
,
,
.

Capabilities.
,
:
<Capabilities>
<Capability Name="internetClient" />
<DeviceCapability Name="webcam" />
</Capabilities>
,
:
Documents Library (documentsLibrary)
. Documents ,
KnownFolders.
,
() File Type Associations,
. ,
-
;
Music Library (musicLibrary)
Music;
Pictures Library (picturesLibrary)
Pictures;
Videos Library (videosLibrary)
Videos;
Microphone (microphone) ;

248

11.
Webcam (webcam)
, .
;
Removable Storage (removableStorage)
.
, Documents
;
Location (location)
( , WiFi
GPS );
Proximity (proximity)
, .
Bluetooth, Wi Fi
;
Internet and public networks (internetClient internetClientServer)
(
) ;
Text messaging or SMS (sms)
, SMS;
Domain credentials (enterpriseAuthentication)
,
;
Home and work networks (privateNetworkClientServer)
(,
);
Certificates (sharedUserCertificates) .
, , ,
.
, .
,
. , Windows 8
, ,
. :
Account Picture Provider
,
. ,

- ;
249

Windows 8 C#
AutoPlay Content
, DVD , . .,

, ;
AutoPlay Device
;
Background Tasks
( ),
;
Camera Settings
;
Certificates ,
;
Contact Picker
, ;
File Open Picker
;
File Save Picker
(
);
File Type Associations ,
;
Game Explorer ,
Windows
;
Print Task Settings
;
Protocol URL-, :
Search
, ;
Share Target ,
,
Share.
, ,
, -,
, .

250

11.


,
.
, Visual Studio,
.
Packaging :

. 11.1.
.
, ,
.


, .
, , ,
, ,
, ,
, .
:
251

Windows 8 C#
<Properties>
<Property>
<DisplayName>ms-resource:dName</DisplayName>
<Description>ms-resource:dDescription</Description>
<Logo>tile.png</Logo>
</Property>
</Properties>
, ms-resource,
,
.


.
Windows App Certification
Kit, Windows 8 SDK.

( ) ,
, .
, , .
Validate Metro style App:

. 11.2.
252

11.
(Launch) :

. 11.3.

. ,

:

. 11.4.
253

Windows 8 C#


Windows
Store, , Store->Create
App Package. Store,
,
:

. 11.5.
Store ,
(
Store). Store
.
, Store,

:

254

11.

. 11.6.
,
: (.cer), (.appx)
bat-,
. Windows 8
.
.
.

255

Windows 8 C#

Windows Store
Windows Store
, .
Windows Store.
Store
, .
,
Microsoft, .
Windows 8 Consumer Preview
,
(https://appdev.microsoft.com/StorePortals).

, Live ID ( ),
:

. 11.7.
.
Windows 7 Internet Explorer 9.
Internet Explorer 10,
.

256

11.
, :
.
,
, , , .
, ,
,
,
GeoTrust, .
,
:

. 11.8.
,
, :

257

Windows 8 C#

. 11.9.
, ,
, .
GeoTrust
. ,
, (
) GeoTrust ,
. : .
live.com, Hotmail.com . . GeoTrust ,
.

258

11.
:

. 11.10.
, :

. 11.11.
259

Windows 8 C#
, .
,
- ,
. , -
. , (
) .

, ( ).
, GeoTrust,
, .


Windows Store, ,
,
:

. 11.12.
Profile
.
( , ,
) .
Account ,
, . . ,
.
260

11.
Explore store trends Financial summary
, ,
.
Submit a new app,
.
.
, , :

. 11.13.
261

Windows 8 C#
8 ,
- . ,
, . ,
.
, .
! ,
, .
,
, :

. 11.14.
262

11.
,
: ; ;
, .
,

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

. 11.15.
Push Notification Service Live Connect.

Web-, Single-Sign-On,
Live
.
:

263

Windows 8 C#

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

264

11.

. 11.17.
,
(,
).
. Microsoft ,
.

265

12.
,

Windows 8 C#
, ,

.
,
.
.

.

. ,
.
.


Windows 8. ,
(. 12.1).

. 12.1.
268

12. ,
4
(. 12.1).

.
:
.
:

,
.

.
.
.
. 12.1.
.

(. 12.2).

. 12.2.
Windows 8 6
. ,
(. 12.3).

269

Windows 8 C#

. 12.3.

(. 12.4).

. 12.4.
(. 12.5), ,
, .
, .
(. 12.6).

. 12.5.
270

12. ,

. 12.6.
-
Windows 8.

,
. . . - .

-
Visual Studio 2011 Beta (. 12.7).

. 12.7.
271

Windows 8 C#
-
, :
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
Assert.AreEqual(string.Empty, );
}
[TestMethod]
public void TestMethod2()
{
Assert.Fail();
}
[TestMethod]
public void TestMethod3()
{
Assert.Inconclusive();
}
}
- Assert,
.
, - .
? Unit Test Explorer.
Quick Launch (
Visual Studio 2011) Unit Test->Windows->Unit Test
Explorer.
Unit Test Explorer
, .
- (. 12.8.)

272

12. ,

. 12.8.

273

Windows 8 C#

,
, ,

. ,
Visual Studio 2011 Express Beta .

Metro
Metro Visual Studio 2012
Express Beta
.
Visual C++, Visual C# Visual Basic
,
.

.

.

Release.
,
Microsoft Store.
Visual
Studio Debug->Start Performance Analysis
Alt+F12 (. 12.9).

274

12. ,

. 12.9.

275

Windows 8 C#

, Visual Studio
.
(. 12.10).

. 12.10.
MSDN
(http://msdn.microsoft.com/en-us/library/windows/apps/hh780914(v=vs.110))

.
:
32- Windows 8:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Xaml]
EnableFrameRateCounter=dword:00000001
64- Windows 8:
[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Xaml]
"EnableFrameRateCounter"=dword:00000001

276

12. ,

(. 12.11).

. 12.11.
,
, GPU .
, .
.

.
,
,

.

277

Оценить