M19: Windows 8 and
Windows Phone 8 Cross
Platform Development
Andy Wigley | Microsoft Technical Evangelist
Rob Tiffany | Microsoft Enterprise Mobility Strategist
Target Agenda | Day 1 Module and Topic | 10-minute breaks after each session / 60-minute “meal break”
Planned
Duration
1a - Introducing Windows Phone 8 Application Development | Part 1 50:00
1b - Introducing Windows Phone 8 Application Development | Part 2 50:00
2 - Designing Windows Phone Apps 50:00
3 - Building Windows Phone Apps 50:00
4 - Files and Storage on Windows Phone 8 50:00
Meal Break | 60-minutes 60:00
5 - Windows Phone 8 Application Lifecycle 50:00
6 - Background Agents 25:00
7 - Tiles and Lock Screen Notifications 25:00
8 - Push Notifications 30:00
9 - Using Phone Resources on Windows Phone 8 50:00
Target Agenda | Day 2 Module and Topic | 10-minute breaks after each session / 60-minute “meal break”
Planned
Duration
10 - App to App Communication 35:00
11 - Network Communication on Windows Phone 8 50:00
12 - Proximity Sensors and Bluetooth 35:00
13 - Speech Input on Windows Phone 8 35:00
14 - Maps and Location on Windows Phone 8 35:00
15 - Wallet Support 25:00
16 - In App Purchasing 25:00
Meal Break | 60-minutes 60:00
17 - The Windows Phone Store 50:00
18 - Enterprise Applications in Windows Phone 8: Architecture and Publishing 50:00
19 - Windows 8 and Windows Phone 8 Cross Platform Development 50:00
20 – Mobile Web 50:00
• Building for Windows Devices
• Consistent Experience
• Tiles, Notifications, Animations
• Differences
• Screen Sizes, Controls, Lifecycle
• Minimizing Development
• Reuse
• Portable Class Library
• Sharing Code
Module Agenda
• Architecture
• APIs
• Visualizing Data
• Navigation
• Compatibility with Windows Phone 7.x
Not Covered in this Module…
Building for Windows Devices
Design Principles for Windows and Windows Phone Applications
Consistent User Experience
Authentically Digital Digital is a valid ‘form’ for
information and doesn’t have
to refer to other forms.
• Pride in craftsmanship
• Be fast and fluid
• Authentically digital
• Do more with less
• Win as one
It’s important to design for the platform differences as well as similarities
Some Key Differences
Screen Size Windows Phone
800x480, 1280x720, 1280x768
Portrait, Landscape
Windows
1024x768
Portrait, Landscape, Snapped
Controls Windows Phone
Panorama, Pivot, ListPicker
LongListSelector
Windows
GridView, ListView, Semantic
Zoom, FlipView
Lifecycle Windows Phone
Launched from start/apps list.
Tombstones apps
Windows
Resumes existing apps
No tombstoning
Demo 1: User Experience
Strategies for sharing in a XAML app
Separate UI from app logic (Model-View-ViewModel)
Share portable .NET code in Portable Class Library
Use common Windows Runtime API (Add as Link)
Complete with platform-specific code as necessary
Separate UI from app logic
User Interface
App Logic
General Model-View-ViewModel (MVVM)
Model-View-ViewModel (MVVM)
Cross-platform app architecture
Reusing pre-built components or libraries
Reuse
Portable Class Library
•Managed Code
•Reusable library
•One codebase with no conditional compilation
Demo 2:
Common code via PCLs
Code Sharing
Reusing code by including code files in multiple projects
Sharing Code
Share Code Files
• Use Add as Link to include same files in multiple
projects
• Change once, Change everywhere
• What to do where platforms don’t match?
Approaches
• #if conditional blocks
• Inheritance
• Partial Classes and Methods
Sharing Code: #if Conditional Blocks
• Enable/Disable lines or chunks of code based on compilation platform
• Existing compilation constants
• NETFX_CORE Windows 8
• WINDOWS_PHONE Windows Phone 8
• Useful for when there are subtle differences in syntax or methods
• Can make code unreadable
Sharing Code: #if Conditional Blocks
#if NETFX_CORE using Windows.UI.Xaml.Media.Imaging; #else using System.Windows.Media.Imaging; #endif
Sharing Code: #if Conditional Blocks
public object Convert(object value, Type targetType, object parameter, #if !NETFX_CORE CultureInfo culture #else string language #endif )
Sharing Code: Inheritance
• Shared functionality in base class
• Platform specific code in sub-class
• Great for separating features that are
specific to individual platforms
• Can make base class abstract to
enforce platform specific
implementations
Sharing Code: Inheritance
/// <summary> /// Base View Model used across both platforms /// </summary> public class AlbumPageViewModel : NotifyBase, IViewModel { ... } /// <summary> /// Sub-class containing additional information used in the Windows application /// </summary> public class WinAlbumPageViewModel : AlbumPageViewModel, ISupportsDesignTimeDataViaCode { }
Sharing Code: Inheritance
/// <summary> /// Abstract base class available across both platforms /// </summary> public abstract class MainPageViewModel : NotifyBase,IViewModel { protected abstract bool NavigatedToSelectedPicture(); } /// <summary> /// Sub-class implementing the abstract method /// </summary> public class WinMainPageViewModel : MainPageViewModel, ISupportsDesignTimeDataViaCode { protected override bool NavigatedToSelectedPicture() { NavigationService.Navigate<WinAlbumPageViewModel>(SelectedPicture.Path); return true; } }
Sharing Code: Partial Classes & Methods
• Shared functionality in one code file eg: DataSource.cs
• Platform specific code in additional code file eg: DataSource.WP8.cs
• Classes are marked as partial and compiled into a single class
• Separates platform specific features
• Can use partial methods as a mechanism to separate out platform specific logic
Sharing Code: Partial Classes & Methods
/// <summary> /// DataSource.cs /// </summary> public partial class DataSource:IDataSource { public async Task<IEnumerable<IFolder>> RetrieveFolders(IFolder root) { ... // other logic var folders = await LoadFolders(root); ... // other logic return folders } } /// <summary> /// DataSource.WP8.cs /// </summary> public partial class DataSource { private async Task<IEnumerable<IFolder>> LoadFolders(IFolder root) { ... } }
Demo 3: Sharing Code
Architecture
Cross Platform Guidance
Architecture
APIs
Visualizing Data
Navigation
Common
Core BCL are the same
Hardware (eg Accelerometer)
Storage
Different
Launchers and Choosers
Sharing
Similar
Protocol registration
Architecture: Identical APIs
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); var accelerometer = Accelerometer.GetDefault(); if (accelerometer != null) { accelerometer.ReadingChanged += AccelerometerReadingChanged; } } void AccelerometerReadingChanged(Accelerometer sender, AccelerometerReadingChangedEventArgs args) { ... }
Architecture: Differing APIs
private readonly CameraCaptureTask camera; public WinPhoneMainPageViewModel() { camera = new CameraCaptureTask(); camera.Completed+=TakePhotoCompleted; } public void TakePhoto() { camera.Show(); } private async void TakePhotoCompleted(object sender, PhotoResult e) { await Task.Run(() => { var ml = new MediaLibrary(); var fileName = string.Format("PhotoManager_{0}.jpg",DateTime.Now.ToString("yyyy_MM_dd")); ml.SavePicture(fileName, e.ChosenPhoto); }); }
Architecture: Near identical APIs
<Extensions> <Extension Category="windows.fileTypeAssociation"> <FileTypeAssociation Name="alsdk"> <DisplayName>SDK Sample File Type</DisplayName> <Logo>images\logo.png</Logo> <InfoTip>SDK Sample tip </InfoTip> <EditFlags OpenIsSafe="true" /> <SupportedFileTypes> <FileType ContentType="image/jpeg">.alsdk</FileType> </SupportedFileTypes> </FileTypeAssociation> </Extension> </Extensions>
<Extensions> <FileTypeAssociation Name="BugQuery" TaskID="_default" NavUriFragment="fileToken=%s"> ... </FileTypeAssociation> </Extensions>
Demo 4: Sharing Photos
Cross Platform Guidance
Architecture
APIs
Visualizing Data
Navigation
Data Binding
Keeps attribute on element on
screen in sync with property on
data object
One or Two way
Converters
MVVM
Code for “use data binding”
Primary principle is separation of
concerns View-ViewModel-
Model
• Write once and the application automatically scales to the device
This is unrealistic and will result in failure!
• Windows and Windows Phone applications need to:
• Be optimized for how they’re going to be used
• Handle dramatically different screen sizes and layouts (eg snapped view)
• Be Pragmatic:
• Develop UX specific to the target platform
• Don’t attempt to share UX resources (styles, controls, pages etc)
• Reuse and share code between platforms
Architecture: Visualizing Data Example of a subhead with an average length
• Model – View – ViewModel
• Design pattern – essentially it means “use data binding”
• How much to data bind
• Some advocates data bind _everything_ to ensure no code in the page
codebehind file
• Some just use event handlers that route through to the current view model
• Overview in the context of Windows and Windows Phone
• View: The pages within your application
• ViewModel: The current state of attributes on the page that may vary
• Model: Any other classes that are used to load/store data
Architecture: Visualizing Data Example of a subhead with an average length
• Simplest way to display data in UI controls is to program them directly to get and set
properties of controls
• e.g. textBox1.Text = "Hello, world";
• In complex applications, such code quickly becomes unwieldy and error prone
• Use XAML data binding to link your Views to your ViewModels
• ViewModels expose the data that is the source for data binding
• UI controls can get their display values automatically from properties of the ViewModel
class
• Changing the property, updates the display
• User input can automatically update the bound property of the ViewModel class
Data Binding 101
• Properties of controls can be bound to a public property of a data object
• In the example above, the Text property of the TextBlock is bound to the LineThree
property of some data source
• Define the data source by setting:
• The DataContext property of any containing FrameworkElement-derived class (a
containing control, the page, or the frame), or
• The ItemsSource property of a List control
Data Binding in XAML
<TextBlock x:Name="ContentText" Text="{Binding LineThree, Mode=OneWay}"/>
• The Mode property determines how changes are synchronized between the target control
and data source
• OneTime – Control property is set once to the data value and any subsequent
changes are ignored
• OneWay – Changes in the data object are synchronized to the control property, but
changes in the control are not synchronized back to the data object
• TwoWay – Changes in the data object are synchronized to the control property and
vice-versa
Data Binding Modes
<TextBlock x:Name="ContentText" Text="{Binding LineThree, Mode=OneWay}"/>
INotifyPropertyChanged
public class ItemViewModel : INotifyPropertyChanged { private string lineOne; public string LineOne { get { return lineOne; } set { if (value != lineOne) { lineOne = value; NotifyPropertyChanged("LineOne"); } } } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { if (null != PropertyChanged) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } }
• Exposing data through bindable properties of your VM is only part of the answer
• The ViewModel needs to do more than simply manage data properties
• What about logic executed as a result of user action such as clicking a button?
Advanced MVVM
Use Commanding to Handle User Actions
• For controls that extend ButtonBase, use the Command attribute to bind the Click event to
a RelayCommand property on your VM
• For other controls and/or events, use Blend InvokeCommandAction on Phone, similar
techniques exist for Windows
Commanding Bind Events to RelayCommand or RelayCommand<T>
<Button Content="Press this" Height="72" Margin="90,464,0,0" Name="button1" Width="300" Command="{Binding HelloCommand}"/>
<ListBox Height="100" x:Name="listBox1" > <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <i:InvokeCommandAction Command="{Binding SelectionChanged}" CommandParameter="{Binding ElementName=listBox1, Path=SelectedIndex}"/> </i:EventTrigger> </i:Interaction.Triggers> </ListBox>
Commanding RelayCommand Implements Logic to Execute public class MainViewModel : ViewModelBase { ... // Note that RelayCommand is NOT in the Silverlight class libraries. This RelayCommand object // comes from the MVVMLight framework. You could create your own implementation – it must implement // the Silverlight ICommand interface. private RelayCommand _myHelloCommand; /// <summary> /// Gets the HelloCommand. /// </summary> public RelayCommand HelloCommand { get { return _myHelloCommand ?? (_myHelloCommand = new RelayCommand( () => { this.WelcomeTitle = "You changed the Title!"; })); } } }
Cross Platform Guidance
Architecture
APIs
Visualizing Data
Navigation and Visual States
Navigation Syntax
Navigation by Uri (Windows Phone)
Navigation by Type (Windows)
View Model Abstraction
Navigation is at View level
Navigation should be at ViewModel
Abstraction is useful
Visual States
Determine the states of the page
Needs to be abstracted to
ViewModel
• Navigation differs (slightly) between the two platform
• Windows: Navigate to the Type of the target page
Eg Frame.Navigate(typeof(MainPage))
• Windows Phone: Navigate to the Url of the target page
Eg NavigationService.Navigate(new Uri(“MainPage.xaml”,UriKind.Relative));
• In both cases Navigation is initiated by code that resides in the View (ie the page)
• Need to abstract and allow it to be driven by the ViewModel
• INavigationService
• Navigation by ViewModel type
• Platform specific implementation
Architecture: Navigation and Visual States Example of a subhead with an average length
Implement a Navigation Service
NavigationService Implementation
public class WindowsNavigationService : INavigationService { private static IDictionary<Type, Type> viewModelRouting = new Dictionary<Type, Type>() { {typeof(WinMainPageViewModel),typeof(MainPage)}, {typeof(WinAlbumPageViewModel),typeof(AlbumPage)} };
private static Frame RootFrame { get { return Window.Current.Content as Frame; } } public void Navigate<TDestinationViewModel>(object parameter) { var dest = viewModelRouting[typeof (TDestinationViewModel)]; RootFrame.Navigate(dest, parameter); } public bool CanGoBack { get { return RootFrame.CanGoBack; } } public void GoBack() { RootFrame.GoBack(); } }
• Get used to creating Services for logic that ‘lives’ outside of the Views and their ViewModels
• Many Benefits:
• Encapsulates logic for a particular function in a separate class
• Lifetime can extend across many different pages
• Define the operations exposed by the service through an interface
• ViewModels work with the interface
• Implementation of that interface can differ between the different platforms
• Examples:
• DataService: Service that exposes the Model data to the ViewModels
• StateService: Service to store the current state or context across multiple pages
Services are Good :)
Demo: View Model Navigation
• Windows Phone 8 and Windows 8 apps share a design language and operate in quite
similar ways
• UX requirements and API incompatibilities make development of a single solution for both
targets impossible
• In general terms, you must develop a different UI for each platform, but much of the rest
of the logic can be shared
• Portable Class Libraries can be used to create class libraries that work directly with both
• Other code can be shared by ‘Add as Link’ and platform-specific code incorporated by
careful use of compile-time constants, inheritance and partial classes
• Careful use of the Model-View-ViewModel pattern can help when separating the UI
implementation from the application logic
Summary
The information herein is for informational
purposes only an 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.
© 2012 Microsoft Corporation.
All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.
MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION
IN THIS PRESENTATION.
Top Related