Upload
windowsphonerocks
View
279
Download
3
Tags:
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
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
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
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
Anatomy of a Windows Runtime App project
Solution nameProject name
Library referencesApp logos and other artwork
App classPage classApp manifest
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
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)
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
Creating a simple app
demo
Container controlsLayout controls
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
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
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*
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
Laying out controls
demo
15
Overview ofWindows XAML controls
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
Common controls“A button is a button is a button…”
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
<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.
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" />
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++.
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.
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.
Optimized controlsSame great API, different UX
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
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
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>
ContentDialog (Phone only)A custom message box to place arbitrary content
Supports both full and partial screen
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 */ }
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();
AutoSuggestBox (Phone only)App code provides suggestions
Automatic positioning to maximize space for suggestions
Fully re-templatable
Windows Phone System UI:AppBar, StatusBar, Soft Buttons
Windows Phone System UI
Status Bar
App Bar
Navigation Bar (Soft buttons)Available on some devicesAlso: In-call UI (not shown)
<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
35
CommandBarWindows Phone
Windows
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
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>
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>
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;
Progress Indicator in Status Bar
Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ShowAsync();var progInd = Windows.UI.ViewManagement.StatusBar.GetForCurrentView().ProgressIndicator;progInd.Text = "Fetching...";progInd.ShowAsync();
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)
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
System UI: AppBar and Status Bar
demo
Styles, Themes and ThemeResources
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
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
Text Enlargement Support
Making eyes happy starting with Windows Phone 8.1
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
Testing for different themes
Use the Device tab in Visual Studio to test your layout
Light themeDark themeHigh ContrastDifferent Accent colors
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>
Styles and Themes
demo
©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.