52
Andy Wigley @andy_wigley Matthias Shapiro @matthiasshap Getting Started Building Windows Runtime Apps WinRT App 29 April 2014 Building Apps for Windows Phone 8.1 Jump Start Building Windows Runtime Apps using C# and XAML

02 getting started building windows runtime apps

Embed Size (px)

DESCRIPTION

Building Apps for Windows Phone 8.1 Jump Start . Videos at: http://channel9.msdn.com/Series/Building-Apps-for-Windows-Phone-8-1

Citation preview

Page 1: 02   getting started building windows runtime apps

Andy Wigley @andy_wigleyMatthias Shapiro @matthiasshap

Getting Started Building Windows Runtime Apps

WinRT App

29 April 2014

Building Apps for Windows Phone 8.1 Jump Start

Building Windows Runtime Apps using C# and XAML

Page 2: 02   getting started building windows runtime apps

In this module…Getting started building Windows Runtime XAML apps…Creating projects in Visual StudioIntroduction to XAML and Page LayoutOverview of the XAML controlsCommon controlsContainer controlsOptimized controlsSignature controls

Using Styles and ThemesProgramming the AppBarProgramming the Status Bar

Page 3: 02   getting started building windows runtime apps

Create Windows Runtime apps using XAML or HTML/JavaScript targeting:

Universal Windows and Windows Phone WindowsWindows Phone

Can also create Windows Phone Silverlight apps targeting Windows Phone 8.0 or 8.1

Creating Projects in Visual Studio 2013

Page 4: 02   getting started building windows runtime apps

Anatomy of a Windows Runtime App project

Solution nameProject name

Library referencesApp logos and other artwork

App classPage classApp manifest

Page 5: 02   getting started building windows runtime apps

XAML and PagesEach of the items on the page can be defined in XAMLEvery XAML element is a declaration of an objectXAML stands for Extensible Application Markup LanguageXAML is a way of describing a UI using XMLThis is a declarative way of expressing your UI

XAML elements are objects in the Windows.UI.XAML namespaceXAML attributes map to setting properties on those objects

Page 6: 02   getting started building windows runtime apps

XAML Display ElementsTextBloc

kTextBloc

k

Image

TextBlock

TextBlock

TextBlock

Grid (Page Container)

StackPanel (stacks controls vertically)

Grid (lays out content in rows and/or columns) – in this case three rows

StackPanel (stacks controls horizontally)

Page 7: 02   getting started building windows runtime apps

Display Element Properties

Each of the elements has properties that define how it appears on the screenPosition on the screenHeight and widthFont color and size etc..

These values are used by XAML when the elements are drawn

Page 8: 02   getting started building windows runtime apps

Creating a simple app

demo

Page 9: 02   getting started building windows runtime apps

Container controlsLayout controls

Page 10: 02   getting started building windows runtime apps

Panel Controls: Canvas, StackPanel, Grid…

Containers for other elementsElements inside the panel are called “Children”You can nest panels

The panel controls how the children are positionedMore on that when we discuss the layout process

Several panels includedBorder, Canvas, StackPanel and Grid cover most common uses

Page 11: 02   getting started building windows runtime apps

StackPanel<StackPanel Width="400" Background="MidnightBlue"> <TextBlock Text="Item 1" FontSize="40" Margin="10"/>

<Rectangle Width="200" Height="50" HorizontalAlignment="Center" Fill="Red"/> <Rectangle Width="200" Height="50" HorizontalAlignment="Center" Margin="-20,-10,0,0" Opacity="0.5" Fill="Orange"/>

<TextBlock Text="The above Rectangle has negative margins" TextWrapping="Wrap" Margin="10" FontSize="40" /> <TextBox Header="First name" FontSize="20" Margin="10" PlaceholderText="Please enter your first name" /> <Button Content="I am a button" Margin="50,100,0,20" /> <StackPanel Orientation="Horizontal" Margin="20"> <Button Content="Fee" /> <Button Content="Fi" /> <Button Content="Fo" /> <Button Content="Fum" /> </StackPanel>

</StackPanel>

Nest

ed

Sta

ckPa

nel

A StackPanel may have

horizontal or vertical

orientation

Marg

ins

and

Alig

nm

ent

Margins and appropriate

alignment are respected

Page 12: 02   getting started building windows runtime apps

Grid<Grid Width="400" Background="DarkBlue" Margin="20">

<Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="120" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> <RowDefinition Height="2*" /> <RowDefinition Height="0.5*" /> </Grid.RowDefinitions>

<Rectangle Stroke="White" Margin="1" Grid.Row="0" Grid.Column="0" /> <Rectangle Stroke="White" Margin="1" Grid.Row="0" Grid.Column="1" /> <Rectangle Stroke="White" Margin="1" Grid.Row="0" Grid.Column="2" />...

<TextBlock Text="Row 0, Col 0" Margin="5" /> <TextBlock Text="Row 0, Col 1" Grid.Column="1" Margin="5" /> <TextBlock Text="Row 0, Col 2" Grid.Column="2" HorizontalAlignment="Right" Margin="5" />...

</Grid>

Rect

ang

les

Row

and C

olu

mn D

efi

nit

ions

Labels

1.0*

2.0*

0.5*

Page 13: 02   getting started building windows runtime apps

Grid<Rectangle Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Fill="CornflowerBlue" /> <Rectangle Grid.Row="2" Margin="-20" Opacity="0.5" Fill="Purple" />

<TextBox Grid.Row="2" Grid.Column="2" Header="This is a TextBox" Margin="5,25,5,5" TextWrapping="Wrap" Text="Notice how I expand to fill all... "/>

<StackPanel Grid.Row="3" Grid.Column="2" Margin="5,25,5,5"> <StackPanel.Resources> <Style TargetType="TextBlock"> <Setter Property="FontSize" Value="14" /> <Setter Property="Foreground" Value="Orange" /> </Style> </StackPanel.Resources> <TextBlock Text="StackPanel Line 1" /> <TextBlock Text="StackPanel Line 2" /> <TextBlock Text="StackPanel Line 3" /> <TextBlock Text="StackPanel Line 4" /> <TextBlock Text="StackPanel Line 5" /></StackPanel>

Nest

ed

Sta

ckPa

nel

Page 14: 02   getting started building windows runtime apps

Laying out controls

demo

Page 15: 02   getting started building windows runtime apps

15

Overview ofWindows XAML controls

Page 16: 02   getting started building windows runtime apps

Converged controls

What’s it really mean?80% exact same XAML 20% custom

Common SignatureOptimized

DatePickerTimePicker

CommandBar

Button

CheckBox

RadioButton

ProgressBar

Slider

ToggleSwitch Hub

PivotListViewGridViewSysTray

Page 17: 02   getting started building windows runtime apps

Common controls“A button is a button is a button…”

Page 18: 02   getting started building windows runtime apps

Text Handling ControlsTextBlockDisplays textSupports line breaks and word wrapping

RichTextBlockParagraphs, spans, and runs allow for formatting sections of the rich text

TextBoxFully templatable Header propertySupports spell-checking, placeholder text, text-prediction and input scope for on-screen keyboards, multi-line support

PasswordBoxObscures text entrySupports placeholder text and templateable Header

Page 19: 02   getting started building windows runtime apps

<TextBox InputScope="EmailSmtpAddress"/>

<TextBox InputScope="CurrencyAmountAndSymbol"/>

<TextBox InputScope="Number"/>

Input scope

Sets layout of on-screen keyboardMany different types available – see documentation for full list

Does not provide any data validation

Implement to provide the most efficient experience to your users.

Page 20: 02   getting started building windows runtime apps

Bu

tton

Con

tent

Button and HyperlinkButton<Button Content="Simple Button" Style="{StaticResource ButtonStyle}"/>

<Button Background="LightBlue" Foreground="Black" Content="Colored Button“ BorderBrush="Orange" Style="{StaticResource ButtonStyle}"/>

<Button Background="White" Foreground="Black" BorderBrush="CornflowerBlue" Style="{StaticResource ButtonStyle}"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="*" /> </Grid.ColumnDefinitions> <Image Source="ms-appx:///Assets/Surface2.jpg" Width="150" Stretch="Uniform" Grid.Column="0" /> <StackPanel Grid.Column="1" Margin="5"> <TextBlock Text="Microsoft Surface 2" Foreground="CornflowerBlue" FontFamily="Segoe UI" FontWeight="Light"/> <TextBlock FontSize="12" Text="This is a button with complex content. ..." Foreground="Gray" TextWrapping="Wrap"/> </StackPanel> </Grid></Button>

<HyperlinkButton FontSize="30" Content="Visit MicrosoftStore.com" NavigateUri="http://microsoftstore.com" />

Page 21: 02   getting started building windows runtime apps

XA

ML

Code-B

ehin

dClick event<Button x:Name="SimpleButton" Content="Simple Button" Click="SimpleButton_Click"/>

private async void SimpleButton_Click(object sender, RoutedEventArgs e){ var dialog = new MessageDialog("The button was clicked.");

dialog.Title = "Button click handler";

await dialog.ShowAsync();}

The click event provides a simple way to handle button interaction directly from the code-behind. Double-click the button on the designer or use Intellisense in the XAML editor to generate the handler.Handlers may also be wired up from code using the += syntax in C# and equivalent in VB or C++.

Page 22: 02   getting started building windows runtime apps

Other types of button controls

ToggleButtonBehaves like a CheckBox, looks like a button.

CheckBox and RadioButtonInherited from ToggleButton to provide the expected functionalitySupports tri-state through null or, in XAML, {x:Null}

AppBarButton, AppBarToggleButtonProvides buttons for use in standard app bars, and also on the main canvas. We’ll cover this when we discuss app bars.

Page 23: 02   getting started building windows runtime apps

ProgressRing and ProgressBar<TextBlock Text="Progress Ring" FontSize="20" Margin="10,10,10,0"/><ProgressRing IsActive="True" Width="80" Height="80" Margin="10,10,10,100"/>

<TextBlock Text="Progress Bar" FontSize="20" Margin="10,30,10,0"/><ProgressBar Minimum="0" Maximum="250" Value="50" Height="50" Margin="10"/>

<TextBlock Text="Indeterminate" FontSize="20" Margin="10,30,10,0"/><ProgressBar Height="50" IsIndeterminate="True" Margin="10"/>

Important!You must deactivate progress rings and progress bars when not visible. There’s a performance penalty if you do not.

Page 24: 02   getting started building windows runtime apps

Optimized controlsSame great API, different UX

Page 25: 02   getting started building windows runtime apps

DatePicker / TimePickerSame API on Windows and Windows PhoneAppropriate UI for platform

Allows restricting to individual segments (show only month/year for example) Window

s

Windows Phone

Page 26: 02   getting started building windows runtime apps

FlyoutsConverged with Windows 8.1

MenuFlyout used to create context menu

New Phone-only flyoutsList Picker FlyoutsDate/TimePicker FlyoutsGeneric Picker Flyouts

All are “light-dismiss”:Dismiss by Back button, or for non full-screen flyouts such as MenuFlyout, dismiss by tapping outside of the control

Page 27: 02   getting started building windows runtime apps

Flyouts<Button Content="Show Normal Flyout" Margin="100, 20, 100, 20"> <Button.Flyout> <Flyout> <StackPanel Width="250"> <TextBlock Text="Some header text" FontSize="24" Margin="0,0,0,20" FontWeight="Light" Foreground="CornflowerBlue"/> <TextBlock Text="This type of flyout is a ..." FontSize="16" TextWrapping="Wrap" /> <Button Content="Do Something" HorizontalAlignment="Right" Margin="0,20,0,0"/> </StackPanel> </Flyout> </Button.Flyout></Button>

<Button Content="Show Menu Flyout" Margin="20, 20, 100, 20"> <Button.Flyout> <MenuFlyout> <MenuFlyoutItem Text="Option 1" /> <MenuFlyoutItem Text="Option 2" /> <MenuFlyoutSeparator /> <ToggleMenuFlyoutItem Text="Toggle Option 1" IsChecked="True" /> <ToggleMenuFlyoutItem Text="Toggle Option 2" /> </MenuFlyout> </Button.Flyout></Button>

Page 28: 02   getting started building windows runtime apps

ContentDialog (Phone only)A custom message box to place arbitrary content

Supports both full and partial screen

Page 29: 02   getting started building windows runtime apps

Programming ContentDialog

private async void ShowContentDialog() { ContentDialog dialog = new ContentDialog() { Title = "Download updates?", Content = "This update will clean the slate for Iron Man", PrimaryButtonText = "Yes, clean it", SecondaryButtonText = "No, Dont!" }; dialog.SecondaryButtonClick += dialog_SecondaryButtonClick;

ContentDialogResult result = await dialog.ShowAsync(); if (result == ContentDialogResult.Primary) { /* do some more Primary logic */ } else if (result == ContentDialogResult.Secondary) { /* else do Secondary logic */ } }

void dialog_SecondaryButtonClick(ContentDialog sender, object args) { /* you can also hook up to a button event handler */  }

Page 30: 02   getting started building windows runtime apps

ContentDialog in XAML

Project -> ‘Add New Item’ -> select ContentDialog

Design your ContentDialog in the same way as a User Control

In code, show your dialog like this:AboutMessage myDialog = new AboutMessage();

ContentDialogResult result =

await myDialog.ShowAsync();

Page 31: 02   getting started building windows runtime apps

AutoSuggestBox (Phone only)App code provides suggestions

Automatic positioning to maximize space for suggestions

Fully re-templatable

Page 32: 02   getting started building windows runtime apps

Windows Phone System UI:AppBar, StatusBar, Soft Buttons

Page 33: 02   getting started building windows runtime apps

Windows Phone System UI

Status Bar

App Bar

Navigation Bar (Soft buttons)Available on some devicesAlso: In-call UI (not shown)

Page 34: 02   getting started building windows runtime apps

    <Page.BottomAppBar>        <CommandBar x:Name="commandBar">            <CommandBar.PrimaryCommands>                <AppBarButton Label="edit" Icon="Edit" />             <AppBarButton Label="favorite" Icon="Favorite" />             <AppBarSeparator />             <AppBarToggleButton Label="play" Icon="Play" />            </CommandBar.PrimaryCommands>             <CommandBar.SecondaryCommands>                <AppBarButton Label="help" Icon="Question" />            </CommandBar.SecondaryCommands>        </CommandBar>    </Page.BottomAppBar>

CommandBar control

34

Page 35: 02   getting started building windows runtime apps

35

CommandBarWindows Phone

Windows

Page 36: 02   getting started building windows runtime apps

Differences from WindowsTop AppBar not supportedAppBar not shown by a gestureCan still set Visibility = "Collapsed" to hide, but when visible, AppBar is not transient on PhoneEquivalent to IsOpen="true" at all timesOn Windows, Top and Bottom AppBar is transient and considered user UI

Can display AppBar minimized on Windows PhoneUse <CommandBar ClosedDisplayMode="Minimal" … /> Not supported on big Windows

Converged XAML but certain properties/events ignored on PhoneIsSticky property, used on Windows to disable the light-dismiss behaviour and keep AppBar visibleOpened and Closed events, which on Windows fires when the AppBar displays/disappears

AppBarSeparator not rendered on Windows PhoneUsed on Windows to render a separator bar onto the AppBar

Page 37: 02   getting started building windows runtime apps

AppBarButton.Icon

Icon Class Icon contents

SymbolIcon

Named Segoe UI Symbol symbol

BitmapIcon A bitmap (PNG, etc.) image

FontIcon A custom font

PathIcon A XAML path

<CommandBar.SecondaryCommands> <AppBarButton Label="Add Item"> <AppBarButton.Icon> <SymbolIcon Symbol="Add" /> </AppBarButton.Icon> </AppBarButton>

<AppBarButton Label="Block"> <AppBarButton.Icon> <BitmapIcon UriSource="assets/foo.png"/> </AppBarButton.Icon> </AppBarButton></CommandBar.SecondaryCommands>

Page 38: 02   getting started building windows runtime apps

AppBarButton MenuFlyouts

<Page.BottomAppBar> <CommandBar> <AppBarButton x:Name="btnBrag" Icon="Camera" Label="brag"> <AppBarButton.Flyout> <MenuFlyout> <MenuFlyoutItem x:Name="menuPhoto" Text="Photo" Click="menuPhoto_Click"/>

<MenuFlyoutItem x:Name="menuVideo" Text="Video" Click="menuVideo_Click"/> </MenuFlyout> </AppBarButton.Flyout> </AppBarButton> <AppBarButton x:Name="btnPinToStart" Icon="Pin" Click="btnPinToStart_Click" Label="Like"/>

</CommandBar> </Page.BottomAppBar>

Page 39: 02   getting started building windows runtime apps

Programming Status Bar

By default, Status Bar is visible and displays with a transparent backgroundThe background color that displays is that of the containing PageCan program the BackgroundColor and BackgroundOpacityThere is no way to control the Status Bar in XAML – code only

Show Status BarWindows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();

Hide Status BarWindows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();

Set Status Bar Background ColorWindows.UI.ViewManagement.StatusBar.GetForCurrentView().BackgroundColor = Colors.Red;

Status Bar OpacityWindows.UI.ViewManagement.StatusBar.GetForCurrentView().BackgroundOpacity = 0.4;

Get size of Status Bar Windows.UI.ViewManagement.StatusBar.GetForCurrentView().OccludedRect;

Page 40: 02   getting started building windows runtime apps

Progress Indicator in Status Bar

Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();var progInd = Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ProgressIndicator;progInd.Text = "Fetching...";progInd.ShowAsync();

Page 41: 02   getting started building windows runtime apps

Application Content Area and System UIContent area automatically resizes as Status Bar and/or AppBar are shown or hidden(0,0) is top left below the Status BarHide the Status Bar and (0,0) moves to top left of screenSimilarly, bottom of the application content area adjusts according to presence of AppBar

If Status Bar is transparent (the default) and AppBar is transparent, what shines through is the Page BackgroundDifferent from Windows where Page Background property is ignored

Developer can override this behaviour and disable automatic content area resizing:ApplicationView.GetForCurrentView().SetLayoutBounds( ApplicationViewLayoutBounds.CoreWindowBounds);

Beware, must handle all resizing yourself when transient System UI displays

(0,0)

Page 42: 02   getting started building windows runtime apps

Soft ButtonsSome devices have soft buttons instead of hardwareIn Phone Settings, user can choose to display always dark, match background or match accent colorButtons always visible when running apps or games

When playing video in Windows XAML Media element in a full window mode• Soft buttons are hidden• Any touch on the screen brings up the soft buttons and transport controls

Page 43: 02   getting started building windows runtime apps

System UI: AppBar and Status Bar

demo

Page 44: 02   getting started building windows runtime apps

Styles, Themes and ThemeResources

Page 45: 02   getting started building windows runtime apps

Style Resources for TextBlock

A limited set of Style resources are supplied in the SDKSuitable for common text display scenarios

Use F12 to examine style definitionIn file C:\Program Files (x86)\Windows Phone Kits\8.1\Include\abi\Xaml\Design\generic.xaml

You can create your own stylesUse BasedOn to base on a supplied styleSet your own Property ValuesDefine in App.xaml or in the Page resources

Page 46: 02   getting started building windows runtime apps

User theme and contrast preferencesOn Windows Phone, users can select light or dark background, and an accent colorApps must work in both dark and light theme, unless they override it

Can also select text size and/or High ContrastApps should respect these settings

Note: Users’ selected accent color is exposed via Color="{ThemeResource SystemColorControlAccentColor}"Can use "{StaticResource PhoneAccentBrush}" when a Brush is needed SystemColorControlAccentColor

Page 47: 02   getting started building windows runtime apps

Text Enlargement Support

Making eyes happy starting with Windows Phone 8.1

Page 48: 02   getting started building windows runtime apps

Theming support in controls

High contrast, text enlargement and theme support built in to all standard controls

Themed & high contrast resources will update on app resume

Light/dark resources update on app resume

Page 49: 02   getting started building windows runtime apps

Testing for different themes

Use the Device tab in Visual Studio to test your layout

Light themeDark themeHigh ContrastDifferent Accent colors

Page 50: 02   getting started building windows runtime apps

Overriding system theme

If you do not override the theme, your app uses the Light or Dark theme selected by the userOverride the theme for your app in app.xaml:

You can also apply the RequestedTheme attribute to any control:<StackPanel RequestedTheme="Light"> … </StackPanel>

Page 51: 02   getting started building windows runtime apps

Styles and Themes

demo

Page 52: 02   getting started building windows runtime apps

©2014 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.