95
Windows 8 and Windows Phone 8 References: MSDN Essential Windows Phone 8

Basics of Windows Phone 8 development

Embed Size (px)

DESCRIPTION

Basics of Windows Phone 8 development (programming for mobile systems using the Microsoft technology)

Citation preview

  • Windows 8 and Windows Phone 8

    References: MSDN Essential Windows Phone 8

  • Overview

  • .NET Stack (1)

  • .NET Stack (2)

    NotesThis architecture is relative to Windows systemsTwo distinct runtime APIs: WinRT and Win32On Win32 we have the .NET client/fullOn WinRT we have the .NET for WinRT

  • Windows Phone architecture evolution

    In Windows Phone 8, the OS moved away from Windows Compact Embedded (WinCE) that was used in WP7 to a new OS which shares its core with the desktop Windows 8

    This means that a bunch of things in the WP8 OS is shared with the desktop implementation, this includes things like kernel, networking, driver framework and others

  • Windows 8 and Windows Phone 8

    The release of Windows Phone 8 is a significant step toward convergence with Windows 8

    Some common native APIs such as DirectX 11, CRT, WinSock, Some (30%) common Windows RT API

    Windows RunTime is a technology first introduced in Windows 8 and which offers a core infrastructure, a common type system, and a standard programming modelBy using common Windows Runtime API in your app, you increase the potential to share code between your Windows Phone 8 and Windows Store apps

    Window RT is extended with phone-specific APIs to form the Windows Phone Runtime API In Windows Phone 8, the .NET Compact Framework has been replaced by CoreCLR, which is the same .NET engine used on Windows 8Windows Phone 8 and Windows 8 have similar but different design guidelines and building blocks used to create your UI

    XAML UI controls for Windows Phone 8 are defined in the System.Windows.Controls and Microsoft.Phone.Controls namespacesthe UI controls for Windows Store apps built using XAML are defined in the Windows.UI.Xaml.Controls namespace

  • Windows RunTime and Windows Phone RunTime

  • Maximizing code reuse between Windows Phone 8 and Windows 8

    Separate UI and app logic using the MVVM pattern Design concepts and XAML controls supported in Windows Phone 8 and Windows 8 are similar, but sharing XAML is not where you should spend your investment; your should reuse the app logic!!

    Share functionality using Portable Class Libraries When you create your app for Windows Phone 8 and Windows 8, you should identify portable code. Place this code in a Portable Class Library and share the portable library between both apps. Portable code has the following characteristics:

    managed code only is supported doesn't use conditional compilation doesn't use Windows RunTime APIs

    There is overlap in the Windows Runtime APIs that are supported on Windows Phone 8 and Windows 8. However, binary compatibility is not supported

    doesn't use UI constructsShare non-portable code with Add as LinkShare your own Windows RunTime componentsShare your own XAML UI controls (limited)

    you can isolate some of your custom basic UI building blocks into UserControls and share those classes as linked files that will be compiled for each platform

    Conditional compilation with preprocessor directives

  • Portable class libraries

  • Universal Windows apps

    Another step towards convergenceHow?

    Install VS 2013 Update 2 RCStart with a Universal App Shared project template, orStart with a Windows Store project and Add Windows Phone 8, Or viceversaAfter that, you'll have 3 projects

    A Windows Store project, a Windows Phone 8 project, and a Shared projectShared project: is a container for resources and code that runs on both platforms

    Shared project vs. Portable class library

  • .NET for Windows Store apps

    .NET for Windows Store apps It is a subset of managed types that you can use to create Windows Store apps The entire set of assemblies for the .NET for Windows Store apps is automatically referenced in your project when you create a Windows Store app using C#

    Windows Store apps vs. Desktop apps

  • Convert .NET apps to Windows Store apps

    When you convert existing .NET Framework code, you should be aware of the following changes you may need to make in your Windows Store app

    You can use many of the same UI typesSystem.Windows Windows.UI.XAML

    The I/O types include new members to support the new await keyword in the asynchronous programming modelSystem.IO.IsolatedStorage Windows.StorageSystem.Net.WebClient System.Net.Http.HttpClient or Windows.Networking.BackgroundTransferSystem.Net.Sockets Windows.Networking.Sockets..............................................................

  • Namespaces

    Together, the .NET for Windows Store apps and the Windows Runtime provide the complete set of types and members available for developing Windows Store apps with C# or Visual BasicManaged types reside in System namespaceWindows RunTime types reside in Windows namespace

  • COM + .NET metadata = WinRT

    WinRT is a language-independent set of deeply integrated OS components that use .NET metadata to make their APIs available to a wide variety of programming languagesWinRT is to Windows Store apps as Win32 is to the desktop

    Much like Win32, WinRT calls typically resolve down to native kernel calls, or for visualization, to DirectX

  • More on WinRT

    Unlike Win32, WinRT was designed from the start to be easily consumed by managed, native, scripting, and other types of languagesWinRT elements

    COM (Component Object Model): is a binary-interface standard for software components; used to enable interprocess communication and dynamic object creation in a large range of programming languagesStandard Win32-style flat DLLs arent self-describing; instead, WinRT components include CLI metadata (which enables a component to state all the types it makes available to outside components) Because all of the built-in WinRT components are native COM

    components, the metadata needs to be external in a .winmd fileProjections build on metadata to provide language-specific versions of the WinRT APIs

  • Windows store app lifecycle

  • Model-View-ViewModel: overview

  • MVVM: details

    A typical MVVM architecture considers one-viewmodel-per-page so the view is the page

    Advice: treat the viewmodel more like a light, page-specific faade into the model and the various service classesThe ViewModel ties the (data) model to the views (UI). It contains the logic with which to manage the data from the model and exposes the data as a set of properties to which the XAML views can bind

    It is a model of the view meaning it is an abstraction of the view that also serves in mediating between the view and the model which is the target of the view data bindingsIt acts as a converter that changes model information into view information

    The role of the controller (in MVC) or presenter (in MVP) of the other patterns has been substituted with the framework binder (e.g., XAML) and view model as mediator and/or converter of the model to the binderThere are two main schools of thought on how a model should be surfaced to the view:

    The underlying model should never be seen by the UI. Instead, you should create separate viewmodel entities that provide view-specific versions of the model entitiesThe viewmodel surfaces model entities directly

  • MVVM impl: model

    Model implthe model class impls INotifyPropertyChanged and the PropertyChanged event (which is reaised when its properties are changed) to notify its views when a property value changes

    class MyModel implements INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string prop1; public string Prop1{ get { return prop1; } set { prop1 = value; property_has_changed(Prop1); } } public void property_has_changed(string pname){ if(this.PropertyChanged!=null) PropertyChanged(this, new PropertyChangedEventArgs(pname)); }}

  • MVVM impl: more

    Modelan alternative is to derive from ObservableObject (which in turn impls INotifyStateChanged) which provides RaisePropertyChanged(string) to notify listeners

    Viewmodelpublic class MyViewModel{ public ObservableCollection data { get; set; };

    ViewThe PhoneApplicationPage instance will set, for a view v: v.DataContext = viewmodel.data;

  • Some WinRT and .NET 4.5 namespaces (1)

  • Some WinRT and .NET 4.5 namespaces (2)

  • XAML, UI and common concepts

  • XAML concepts

    XAML is the markup language for building WPF / Silverlight / Windows 8 / Windows Phone apps

    it's a sort of serialization format that works well with toolsA XAML element ties itself to the name of a class

    classes must allow for empty constructorsThe XAML file is parsed and an object graph that follows the same structor of the XAML file is loaded into memoryObject properties are specified as strings converted to opportune objects, e.g.: the following are equivalent

    XAML elements can be named so that they'll be available to other XAML elements or the code-behind file

    ... Name is defined by FrameworkElement

  • More on XAML (1)

    Namescopes

    A transform is used to change the way an object is rendered without having to change its properties

    e.g. TranslateTransform to move an objectColors can be specified by name (e.g. Pink), #rrggbb or #aarrggbbProperty paths provide a way to reference properties of objectsProperties can be set in a variety of ways. The DependencyObject and DependencyProperty classes are part of a system that helps maintain order by establishing priorities for the different ways in which the property might be set

  • Dependency property precedence rules

  • Some components

    TextBlockContentPanelShape is base class for Line, Rectangle, Ellipse, Polygon, PolyLine, PathBrushes are used to paint surfaces

    SolidColorBrush, LinearGradientBrush, RadialGradientBrush, ImageBrush, VideoBrush

    Image

  • XAML controls

    Control supports direct interaction with the userSimple controls: PasswordBox, TextBox, Slider, ProgressBar

    RichTextBox allows the display of formatted text its content can use markup tags such as , , ,

    ......Content controls: allow you to contain arbitrary XAML inside them (Content property); these derive from ContentControl class

    Button, CheckBox, RadioButton, HyperlinkButtonList controls: show any arbitrary list of items (ItemsSource property, taking any collection that supports IEnumerable or IList)

    ListBox,They can use DataTemplates to customize the look of individual items in the list

    InteractionsDevices without a physical keyboard use a Software Input Panel (SIP)

    with InputScope = Text|Chat|URL|EmailSmtpAddress|Date|... you can change the SIP

  • Data binding (1)

    Every binding includesAbinding source, which is an object with data that you want to render Abinding target, which is aDependencyPropertyof aFrameworkElementfor rendering the data ABindingobject, which moves the data between the source and target, and can reformat it using an optionalvalue converter.

    The binding engine gets information from theBindingobject about the followingThe source and target objectsThe direction of the data flow (Binding.Mode ) The value converter, if present; set via theConverterproperty to an instance of a class that implementsIValueConverter Other settings, such asFallbackValueandTargetNullValue

    For changes to the source object to propagate to the targetthe source must implement theINotifyPropertyChanged interface, which has only thePropertyChangedevent

    For example, ObservableCollectionclass is a good collection choice for data binding, because it implements the INotifyPropertyChangedandINotifyCollectionChangedinterfaces

  • Data binding (2)

    When the bindings pull their data, they'll look for a source, and when they don't have one, they'll search for the first non-null data source in the hierarchyData binding modes

    OneTime: pulls data from a source onceOneWay (default): as the source's data changes, it pulls those changesTwoWay: it also pushes changes back to the source as the data changes in the control (normally on the control losing focus)

  • Data binding (3)

    If you are binding several properties to a common source, you want to use the DataContext property, which provides a convenient way to establish a scope within which all data-bound properties inherit a common sourceAlternatively, if you want to specify the source on your individual bindings explicitly, you have the following options:

    Source: If you do not need the functionality of establishing a scope in which several properties inherit the same data context, you can use the Source property instead of the DataContext property

    you can use it to override the inherited data contextRelativeSource: when you want to specify the source relative to where your binding target is

    e.g. when you want to bind one property of your element to another property of the same element or if you are defining a binding in a style or a template

    ElementName: You specify a string that represents the element you want to bind to. This is useful when you want to bind to the property of another element on your application

  • More on data binding

    When binding against large collections, you can improve performance byusing delay-load for images ( images not loaded until they can be seen)

    changing scrolling responsibility from OS to the control

    You can format the data directly in the binding

    Element binding: you can bind two XAML elements

    Converters are classes implementing IValueConverter ( Convert and ConvertBack) that allows the binding of properties of different types

    Converters are typically created as resources And referenced via {Binding b, , Converter={StaticResource myConv}}

  • XAML visual containers

    Grid: table-like layout of columns and rowsRow/ColumnDefinitions contain Row/ColumnDefinition objectsThe Grid's children can specify values for Grid.column and Grid.row attached properties

    StackPanel: horizontal/vertical stacking of individual elementsCanvas: position-based layout (via top and left positions)ScrollViewer: container that can be larger than the contents to allow users to scroll through itBorder: to create a simple border around a single element

  • XAML Transformations and animations

    TransformationsCan be added by assigning the RenderTransform propertyExamples of transforms include

    RotateTransform, SkewTransform, ScaleTransform, TranslateTransform (for movement), CompositeTransform (to combine the others)

    Animations are a way to change XAML properties over time Are named after the type of property they change

    DoubleAnimation, ColorAnimation, PointAnimation They're housed in a container called StoryBoard The attached properties StoryBoard.TargetName/TargetProperty on animations specify the target object's name and its propertyTo change the way the values are interpolated, you can use

    keyframe animations : at a specific time of the animation you assign some values that can be used for calculationseasing functions : are applied against timeline animations to change the nature of the interpolation

  • Reuse in XAML

    Common resources (e.g. colors, brushes...)Reusable objects must be declared in a section and identified with an x:Key attribute

    Every subclass of FrameworkElement supports a collection of Resources We can refer to such objects via {StaticResource resName} markup extension To share resources across projects, you can use resource dictionaries (XAML files to be imported into other XAML files)

    Common stylesStyle objects allow you to create sets of properties

    ...TargetType specifies the type of elements to which the style can be applied

    Can be applied using: Style={StaticResource myStyle} If your style does not include the Key attribute, it is an implicit style and is applied by default to its TargetType

  • Touch

    Two kinds of touch interactions (manipulations)when the user drags her finger on the screenwhen the user uses a pinch move to resize objects

    Silverlight has 3 events to allow to use this touch infoManipulationStarted, ManipulationDelta, ManipulationCompleted

    ManipulationDeltaEventArgs.CumulativeManipulation.Translation contains the extent of the drag operation

  • Layout in WinRT XAML

    Whenever elements need to be rendered to screen, the layout system is invoked for an asynchronous layout passIn the measure pass, the layout system asks each element to provide its ideal dimensions given a provided maximum sizeIn the arrange pass, the layout system tells each element its final size and requests that it lay itself outMeasure + arrange is a layout pass Layout information is retained from frame to frame and is recalculated only when necessary

  • UIElement layout properties

    Width. Height, Padding, Margin, Horizontal/VerticalAlignmentDuring layout, the panel that owns the element can modify the size of the element if necessary

    Changing ActualWidth and ActualHeight If they're not set, they can be zero or double.NaN check them

    LayoutUpdated is the last event fired before an element is ready to accept input

    it is the safe location for inspecting the actual size and position of the element

  • More on layout properties

  • Basic techniques

  • Localization

    Supported by the Visual Studio templateString res file with localizations: Resources/AppResources.resx AppResources class is generated

    so that you can refer to strings via AppResources.MyStr LocalizedStrings that wraps AppResources is generated so that it can be used in data binding

    it includes a property LocalizedResources that returns the AppResources obj

    From codeCreate a ResourceDictionary of strings then

    ResourceLoader resLoader = new ResourceLoader();String myLocalizedStr = resLoader.GetString(stringKey);

  • Serialization

    XML serialization (add System.Xml.Serialization assembly ref)XmlSerializer ser = new XmlSerializer(typeof(MyType));ser.Serialize(wrStream, myObj);var reader = XmlReader.Create(fileSerialization);if(ser.CanDeserialize(reader)){ myObj = (MyType) ser.Deserialize(rdStream);

    JSON serialization DataContractJsonSerializer This class is part of the WCF classes available in Windows Phone SDKIt lives in System.Runtime.Serialization but is impl in System.ServiceModel.Web assembly (which need to be included)var s = DataContractJsonSerializer(typeof(MyType));s.WriteObject(file, someInstance);someInstance = (MyType)s.ReadObject(anotherfile);

  • Windows Phone 8 Basics

  • Screen

  • Layout: hubs

    HubIs the basis for layout of universal windows appsProvide a starting point to get the user to use natural curiosity to learn what is available in the appUsually these hubs take the form of apps that are larger than the (phone) screen (Panorama applications)

  • Windows Phone requirements (1)

    Hardware requirementsScreen resolutions: 480x800, 768x1280, 720x1280Capacitive touch with at least 4 points of touch controlMemory: 256KB RAM, 8GB FlashSensors: A-GPS, Accelerometer, Compass, Light and Proximity, GyroCPU: ARM7 Scorpion/Cortex or better; multicore processors now supportedCamera: 5 megapixels minimum, flash requiredBluetoothMultimedia: Codec acceleration; support for DivX 4-5-6, H.264 High ProfileWi-Fi 802.11gNFCFM radio receiver

  • Windows Phone: inputs

    Requirements in terms of hardware inputsPower buttonVolume controlTouch screenCamera buttonBack buttonStart buttonSearch button

    Input patternsTouchKeyboards (hw and sw)Hardware buttonsSensors

  • Windows Phone Store

    The Windows Phone Store is the only choice Handles billing via credit card or operator billing Gives you 70% revenue Allows apps to be updated without cost (regardless of whether it is a paid, free, or

    ad-supported app) Lets you deliver trial versions of apps and convert them to full versions Handles automatic updating of your app

    To distribute through the Store, you have to join the Windows Phone App Hub ($99 per year)App Hub Submissions

    Creating an app and packaging as a .xap file Microsoft verifies the .xap file is valid and asks you to enter additional metadata Next, Microsoft certifies the app for quality and checks for the Store policies Finally, Microsoft signs the .xap with a certificate and posts it to the store

  • Windows Phone API

  • Start off

    Install the Windows Phone SDK The emulator requires Windows 8 Professional 64-bit version (this is because it's a Hyper-V image)

    it does not work well in a virtual machine and is not officially supportedInstall Visual Studio (Express) and Blend (Express)Create a new project with the Windows Phone App template

    it will prompt a dialog box with the version of the phone to target (7.1 or 8)MainPage.xaml is the main design document for your new app you can right click and select Open in Blend to design using Blend root element is a

    App.xaml and related App class represent the applicationIn WMAppManifest.xml the NavigationPage represent the starting page of the application and points by default to MainPage.xaml

  • The Application

    The App classis where we can store application-wide resourced

    the App class (extending Application) that goes with App.xaml represents the application itself it stores the main PhoneApplicationFrame

    The Application instance is exposed as a singleton via App.Current

  • Tombstoning

    Tombstoning gives the user the illusion of multitasking

  • Tombstoning: details

    When your app is visible on the screen it is in running state When something interrupts your app, it is notified to be deactivated

    here you can save data / stateWhen deactivation is completed the app is in a dormant state

    here all threads are suspended and no processing continuesIf the OS needs the memory occupied by your app, the app is removed from memory and moved to a tombstoned state

    but data saved during deactivation is retainedIf the user returns to your app, the app is notified to be activated

    here you can restart your app or restore the saved state

    This process is exposed to the developer via the PhoneApplicationService class

    The App.xaml creates an object of this class and registers the hooksPhoneApplicationService.Current always points to the current service for the applicationPhoneApplicationService.Current.State is an IDictionary which can be used to save/restore the app state

  • Page-based navigation

    As the user navigates to other pages, the stack of pages growsNavigation

    you can explicitly exit your app via Application.Terminate() You can interact with navigation facility using NavigationService objects which can be retrieved via

    ApplicationPage.NavigationService property directly on PhoneApplicationFrame objects

    Methods: Navigate(URI), GoBack(), RemoveBackEntry()

    Subclasses of Page can leverage on hooks such as OnNavigatedTo(), OnNavigatingFroM(), OnNavigatedFrom() The NavigationContext class and NavigationEventArgs objects provide utility method/properties for tuning the navigation logic

    NavigationContext.QueryString

  • Windows Phone concepts

    Tasks (Microsoft.Phone.Tasks ns) are interactions with the phoneOn the phone, only one application can be running at a time

  • Phone-specific UI controls

    Panorama: creates a virtual canvas of several panels that the user can scroll into view as she wants

    Panorama.Titleit requires to add a reference to the Microsoft.Phone.Controls assembly contains many

    Pivot: also used to show multiple sections, but it can handle more items than Panorama

    A pivot section takes the entire width of the page instead of having overlapping sectionsHeaders at the top of the page show both the currently selected section and other pages that are not currently selected contains many

  • Tasks

    e.g., CameraCaptureTask, PhoneCallTask, SearchTask, WebBrowserTask, They are instantiated and then launched by calling Show() As the app can be deactivated, the task objects should be class members so that they're wired up when the app is re-activated

  • Phone hardware

    Vibration (haptic feedback) overuse is discouraged for batteryrecommended for actions for which it's difficult to use visual cueMicrosoft.Devices.VibrateController.Default.Start(TimeSpan.FromMilliseconds(100));

  • Accelerometer

    It's a sensor that helps determine the phone's speed and direction based on its relationship to gravity

    Microsoft.Devices.Sensors.Accelerometer

    Accelerometer acc = new Accelerometer();acc.TimeBetweenUpdates = TimeSpan.FromSeconds(1);acc.CurrentValueChanged += myHandler;acc.Start();...void myHandler(object s, SensorReadingEventArgs e){ var pos = e.SensorReading.Acceleration; // then we update the UI Dispatch.BeginInvoke( () =>{ xValue.Text = pos.X.ToString(0.00) });

  • Storing data

    Two main ways to store dataStorage: allows to store data as files in a virtualized filesystem that only your app has access toLocal database

    requires many resources! you need to ask if you really need it

  • Storage (1)

    Three types of storageLocal folder: is allocated in a separate private part of the internal filesystem

    Access via isolated storage classes from .NETor (better) the Storage API from WinRT (Windows.Storage ns)

    var folder = ApplicationData.Current.LocalFolder; var f = await folder.CreateFileAsync(f.txt, CreateCollisionOption.ReplaceExisting);using(var stream = await folder.OpenStreamForReadAsync(foo.txt)){ } var f = await StorageFile.GetFileFromApplicationUriAsync(new Uri(ms-appdata:///local/x.txt));

  • Storage (2)

    Application folder (read only) You can use URIs such as: ms-appx:///myfile.txt installation directory if you mark any file as Content in your project, it'll be packaged with

    the code and delivered to the installation dirExternal storage (read only) var devices = await ExternalStorage.GetExternalStorageDevicesAsync();var sdCard = devices.FirstOrDefault();if(sdCard!=null){ var file = await sdCard.GetFileAsync(file.txt);

  • Isolated storage

    IsolatedStorageSettings is a class that represents access to a simple dictionary of things to store in the phone

    so that you don't need to impl a full serialization schemeIsolatedStorageSettings store = IsolatedStorageSettings.ApplicationSettings;if(store.contains(key)){ var x = store[key]; }

    if you need to store complex types, these must be compatible with XML serialization

  • Windows 8 Development Basics

  • Intro

    Windows 8 introduces a new style of application: Windows Store apps They are based on new sets of API

    known as Windows Runtime which supports langs such as C++, C#, HTML5 and JavaScript

    and WinJS (JavaScript API)the WinJS namespace covers functionality that is similar to the Windows.UI.XAML ns

    WIndows RT and WinJS are supported only in Windows Store apps are not supported in desktop apps or browsers

    These Windows Store appscan run full-screen or snapped to the side of a screencan provide toast (notifications that you show to users when your app is in the background) or animate their tiles on the Start screen with dynamic contentscan use contracts, a collection of hooks to provide common functionality that can integrate with other apps, including search and sharingrun within a sandboxed environment, and require permissions to access certain functionality

  • Windows Store apps characteristics

    Windows Store appscan support different layouts and views to create a great user experience across a variety of form factors and display sizesuse tiles (on Start screen) instead of icons to be launched and also to deliver contentthe app bar to present commands and tools to users

    it is hidden by default and appears when users swipe a finger from the bottom edge of the screenthe navigation bar is used to present navigation options to users (it can contains a list or lists of links)

    hidden by default; it appears when users swipe a finger from the top edge of the screenthe charms are a consistent set of buttons that appear in every app: search, share, connect, settings, and startwork smoothly with a variety of input sources, including touch, pen, mouse, and keyboard input

    You can use a single set of events that work for all these input sourcescan interact with other apps and even share content with other apps by supporting the right app contracts can store data in the cloud

  • Windows Modern style: principles

    PrinciplesTake pride in craftsmanship

    look for beautiful code and beautiful designBe fast and fluid

    be responsiveBe authentically digital

    be connected with the cloud; be dynamic and alive in interactionDo more with less

    be focused and directWin as one

    take advantage of user's knowledge of the Win 8 platform; use standard interaction patterns; work with other apps using contracts

  • Windows Modern style: details

    Typography is important for emphasisRecommended font sizes

    Page headers: 42; Subheaders: 20; Third level: 11; Tertiary info: 9The font used is typically a Segoe variant such as Segoe UI

  • App architecture

    App model architecturePresentation technologies: XAML, HTML5, DirectX Asset

    [JS] images/ [C#] Assets/ Async programming

    [JS] Common JS Promises [C#] async/await keywordsPackaging and deployment: Package.appxmanifest

    tune it by using the Manifest Designer in Visual Studio

  • The sandbox

    The user is protected via 4 main waysWinRT and the .NET 4.5 subset for Windows Store apps expose only safe APIs The code runs in a low-access, isolated space, sometimes referred to as the LowBox. The Windows app store verification tools perform a static analysis and make sure your app isnt accessing anything it shouldnt.

  • App lifecycle

    Much like Windows Phone apps, Windows Store apps suspend when they are no longer used, yet they remain in memory

    (Low memory)OnLaunched (from Object)OnActivated ((from Object)(invoked when app activated by means other than normal launching)

  • App lifecycle management

    Activating an appOverride OnLaunched (called whenever the user launches the app) The LaunchActivatedEventArgs parameter contains the previous

    state of your app and the activation arguments Restore application data if PreviousExecutionState equals to Terminated or ClosedByUser ; if it is NotRunning, it means that the app failed to save its application data successfully

    Suspending an appOverride Suspending Save application data before suspension & release resources

    Resuming an appOverride Resuming (called when the user switched away from your app and then back to it)Refresh displayed content after suspension

  • Events

    The UIElement class defines all the basic user-input events:eight events beginning with the word Pointer that consolidate input from touch, the mouse, and the pen;

    PointerCanceled, PointerCaptureLost, PointerEntered, PointerExited, PointerMoved, PointerPressed, PointerReleased, PointerWheelChanged

    five events beginning with the word Manipulation that combine input from multiple fingers;ManipulationStarting, ManipulationStarted, ManipulationDelta, ManipulationInertiaStarting, ManipulationCompleted

    two Key events for keyboard input (KeyDown, KeyUp); andhigher level events named Tapped, DoubleTapped, RightTapped, and Holding

    RightTapped its mostly used to register right-button clicks on the mouse, but you can simulate a right tap with touch by holding your finger down for a moment and then lifting, a gesture that also generates Holding events

    GotFocus and LostFocus signal when an element is the target of keyboard input; andDragEnter, DragOver, DragLeave, and Drop relate to drag-and-drop

  • Handling events

    e.g., An elem that derives from UIElement fires a Tapped event to indicate that the user has briefly touched the element with a finger, or clicked it with the mouse, or dinged it with the penFor the Tapped event to work

    The IsHitTestVisible and IsTapEnabled properties must both be set to their default values of true. The Visibility property must be set to its default value of Visibility.Visible

    // in my page classprivate void my_handler_in_codebhind_file(object sender, TappedRoutedEventArgs e){ }

  • Routed events

    Routed events: are types of events that can invoke handlers on multiple listeners in an element tree, rather than just on the object that raised the event Routing strategies

    Bubbling: Event handlers on the event source are invoked. The routed event then routes to successive parent elements until reaching the element tree rootDirect: Only the source element itself is given the opportunity to invoke handlers in responseTunneling: From the element tree root to the routed event source

    All routed events share a common event data base class, RoutedEventArgs, which defines the following properties

    Handled: if set to true, then the event is effectively inhibited from further processing higher in the visual tree OriginalSource Source

  • The app bar

    Its where youd put functionality normally thought of as menu and toolbar options in desktop appsThe app bar control is surfaced through the TopAppBar and BottomAppBar properties of the Page Its a ContentControl you may put any type of control in it.

  • Splash screens

    The purpose of the splash screen is to provide a transition from the Start page to your app; this is displayed by Windows when loading your appTo create a basic splash screen for your app, you need to do two things

    Design an image and background color Configure the appx manifest with those values

    To extend the splash screen, you use the SplashScreen class in concert with a dedicated splash screen page

    in App.xaml.cs:protected override void OnLaunched(LaunchActivatedEventArgs e){ if(e.PreviousExecutionState!=ApplicationExecutionState.Running){ var splash = new MySplash(e.SplashScreen); Window.Current.Content = splash; } Window.Current.Activate(); DispatcherHelper.Initialize(); }

  • Tiles

    The basic tile (logo image, background color, optional foreground text) can be configured in the appx manifest designer

    Just as with splash screens and other images,you should provide the square and, if used, wide tiles in the three DPI formats: 100%, 140%, and 180%

    Secondary tiles are shortcuts, or deep links, into your appWinRT supplies the SecondaryTile class

    Live tiles are tiles that show updates from the apps they represent

    The app can send notifications to the tile

  • Toast notifications

    Toast notifications are useful when your app may not have focus or the part of the app that generated the notification is no longer in focus

    Whereas tile notifications are informative and enticing, toast notifications are time-sensitive and potentially urgent

    Toasts must be specifically enabled in the appx manifestvar toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText02);// update toastXml to set toast paramsvar toast = new ToastNotification(toastXml);var notifier = ToastNotificationManager.CreateToastNotifier();notifier.Show(toast);

  • View states (1)

    Windows 8 Modern apps have a more standardized approach to keeping multiple apps open at the same time

    This is accomplished using a docking metaphorView states are the four main forms an app can take when presented onscreenWindows 8 XAML has built-in support to help you manage view states and screen orientationIn the Windows Store, all apps must support the four views: full screen (portrait and landscape), snapped, and filled

  • Snap views

    A Windows 8 machine requires a display of at least 1024 768 pixels to run Windows Store applications. This display size has an aspect ratio of 4:3On a tablet, the screen can switch between landscape and portrait modes, so a display size of 768 1024 will also be encounteredIn addition, 1366 768 (approximately 16:9) is the smallest display size that supports snap modes In Windows.UI.ViewManagement ns, ApplicationView.Value indicates the current ApplicationViewState value

    Values: FullScreenPortrait, FullScreenLandscape, Filled, SnappedIf your programneeds to be notified when the view changes, check the value during a SizeChanged handler

    The Snapped view is always 320 units wide The Filled view is always the total screen width minus 320 units for the other application minus 22 units for the drag bar

  • Visual state

    VisualStateManager.GoToState(control, ApplicationView.Value.ToString(), false);

  • Screen resolution issues

    For example, a 1024 768 pixel screen has a diagonal of 1280 pixels. If the screen measures 12 inches diagonally, thats a resolution of 106 DPI (Dots Per Inch)The Windows Runtime refers to the assumed resolution of the video display as a logical DPI Normally, the logical DPI is 96, but for displays of high pixel density, logical DPI can be either 134.4 (that is, 96 DPI scaled by 140 percent) or 172.8 (96 DPI scaled by 180 percent)

    i.e., when your program runs on a physically small screen with a high pixel density, Windows scales these coordinates and sizes by 140 percent or 180 percent

    So sizes in XAML are actually device-independent units (DIUs) e.g., a FontSize of 20 on a display with 180 percent resolution scale is actually a 36-pixel FontSize font

    Scaling bitmaps would make them larger and fuzzier, so you can create bitmaps in three different sizes and let Windows select the correct one

    e.g., 200-pixel-square, 280-pixel-square, and 360-pixel-square

  • Scaling issues

    When your program runs on a physically small screen with a high pixel density, Windows scales these coordinates and sizes by 140 percent or 180 percent, depending on the display size and resolutionInstead of pixels, we talk about Device-Independent Units (DIU) Text and vector graphics are scaled without loss of resolutionFor bitmaps, you create them in three different sizes

    e.g. 200-pixel-square, 280-pixel-square, and 360-pixel-squareIt is possible to store these images as program assets and have Windows automatically select the correct one

    e.g. ImagesA/img1.scale-100.jpg | img1.scale-140.jpg OR, ImagesB/scale-100/img2.jpg ... ImagesB/scale-140/img2.jpg

  • Deployment

    Any individual application destined for store distribution is packaged into an app package with the .appx extension

    One key difference from a Silverlight .xap, however, is that during development, the .appx isnt automatically created

  • App data stores

    Data storeslocal: persistent data that exists only on the current device.roaming: data that exists on all devices on which the user has installed the apptemporary: data that could be removed by the system at any time.If your app is removed, these data stores are deleted

  • Local app data

    Get the containers for the app's settings and filesApplicationDataContainer settings = ApplicationData.Current.LocalSettings;StorageFolder localFolder = ApplicationData.Current.LocalFolder;

    Write datasettings.Values[key] = myValue;

    MoreApplicationDataaContainer newCont = settings.CreateContainer(MyNewContainer, Windows.Storage.ApplicationDataCreateDisposition.Always);settings.Containers[MyNewContainer].Values[k] = v;

    (Async) File I/OStorageFile sampleFile = await localFolder.CreateFileAsync("dataFile.txt", CreateCollisionOption.ReplaceExisting);await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));StorageFile sampleFile2 = await localFolder.GetFileAsync("dataFile.txt");String timestamp = await FileIO.ReadTextAsync(sampleFile2);

  • WinRT XAML: panels (1)

    A panel can contain any number of child elems in Children prop

  • WinRT XAML: panels (2)

    Canvas Elements on a canvas are positioned simply using Canvas.Left (X), Canvas.Top (Y), Canvas.ZIndex attached properties the higher the ZIndex, the higher the elem is on the layout stack

    StackPanel: children are positioned adjacentlyOrientation=Horizontal|VerticalUnless given an explicit size, the StackPanel will be sized to the widest element when in vertical orientation or the tallest element when in horizontal orientationIn vertical (horizontal) orientation, you can use HorizontalAlignment (VerticalAlignment) to Stretch to make the elem have full width (height)The VirtualizingStackPanel is a version of the StackPanel control built for smooth performance with large numbers of child elements using a technique known as UI virtualization can only be used inside of an ItemsControl such as a ListBox

  • WinRT XAML: panels (3)

    Grid

    ...

    Sizing: logical pixel, auto (sized to the content), * (remaining space) Note that * can have an associated multiplier

  • Custom controls

    // 0) Custom controls are classes that derive from UserControlpublic class MyControl : UserControl {

    // 1) Create and register the dependency property public static readonly DependencyProperty XProperty = DependencyProperty.Register("X", typeof(TypeOfX ), typeof(MyControl), new PropertyMetadata(null, new PropertyChangedCallback(xChanged))); // 2) Create the back-end property public TypeOfX X { get { return (TypeOfX)GetValue(XProperty); } set { SetValue(XProperty, value); } } // 3) Create a handler to be called when the dependencyproperty changes private static void xChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { MyControl me = d as MyControl; /* can obtain instance to do something */ }}

  • Orientations

    Windows.Graphics.Display ns defines an enumeration DisplayOrientations with 5 values

    None: Used only for DisplayProperties.AutoRotationPreferencesLandscape: 90 degrees clockwise rotation from PortraitFlippedPortrait: 90 degrees clockwise rotation from LandscapeLandscapeFilled: 90 degrees clockwise rotation from PortraitPortraitFilled: 90 degrees clockwise rotation from LandscapeFlipped

    The static DisplayProperties.NativeOrientation property tells the orientation of the screen that is native or most naturalThe DisplayProperties.OrientationChanged event is fired when CurrentOrientation changes (as a result of the user turning the screen) or NativeOrientation changes, which happens more rarely when an application is moved to another monitor

  • Page navigation

  • LayoutAwarePage

    It's a page, generated by VS2013, which provides conveniences:App view state to visual state mappingGoBack, GoForward, GoHome event handlersMouse and Keyboard (e.g. Alt+RightArrow) shortcuts for navigationState management for navigation and process lifetime managementA default view model

  • LayoutAwarePage: default view model

    public class LayoutAwarePage : Page { public static readonly DependencyProperty DefaultViewModelProperty = DependencyProperty.Register("DefaultViewModel", typeof(IObservableMap), typeof(LayoutAwarePage), null) protected IObservableMap DefaultViewModel { get { return this.GetValue(DefaultViewModelProperty) as IObservableMap; } set { this.SetValue(DefaultViewModelProperty, value); } }}

    public class WinStore.Pages.HomePage : LayoutAwarePage { // TODO: Assign a bindable group to this.DefaultViewModel["Group"] // TODO: Assign a collection of bindable items to this.DefaultViewModel["Items"] }

    Slide 1Slide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Slide 10Slide 11Slide 12Slide 13Slide 14Slide 15Slide 16Slide 17Slide 18Slide 19Slide 20Slide 21Slide 22Slide 23Slide 24Slide 25Slide 26Slide 27Slide 28Slide 29Slide 30Slide 31Slide 32Slide 33Slide 34Slide 35Slide 36Slide 37Slide 38Slide 39Slide 40Slide 41Slide 42Slide 43Slide 44Slide 45Slide 46Slide 47Slide 48Slide 49Slide 50Slide 51Slide 52Slide 53Slide 54Slide 55Slide 56Slide 57Slide 58Slide 59Slide 60Slide 61Slide 62Slide 63Slide 64Slide 65Slide 66Slide 67Slide 68Slide 69Slide 70Slide 71Slide 72Slide 73Slide 74Slide 75Slide 76Slide 77Slide 78Slide 79Slide 80Slide 81Slide 82Slide 83Slide 84Slide 85Slide 86Slide 87Slide 88Slide 89Slide 90Slide 91Slide 92Slide 93Slide 94Slide 95