03 page navigation and data binding in windows runtime apps

38
Andy Wigley @andy_wigley Matthias Shapiro @matthiasshap Page Navigation and Data Binding in Windows Runtime Apps WinRT Apps 29 April 2014 Building Apps for Windows Phone 8.1 Jump Start Building Windows Runtime Apps using C# and XAML

Upload: windowsphonerocks

Post on 24-May-2015

487 views

Category:

Technology


0 download

DESCRIPTION

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

TRANSCRIPT

Page 1: 03   page navigation and data binding in windows runtime apps

Andy Wigley @andy_wigleyMatthias Shapiro @matthiasshap

Page Navigation and Data Binding in Windows Runtime Apps

WinRT Apps

29 April 2014

Building Apps for Windows Phone 8.1 Jump Start

Building Windows Runtime Apps using C# and XAML

Page 2: 03   page navigation and data binding in windows runtime apps

Navigating between Pages in Windows Runtime XAML apps…• Forward navigation• Hardware Back key handling• Navigation history

Data binding• Data binding in XAML• Building data classes

Using Design-time Data

In this module…

Page 3: 03   page navigation and data binding in windows runtime apps

Page navigation

Page 4: 03   page navigation and data binding in windows runtime apps

Windows, Frames and Pages

Window

The window contains a single frame, sized at 100% of area.The frame contains pages, also typically sized at 100% of the area available to the window.In Windows Store Apps for Tablet/PC, apps may have more than one window. On phone, apps have only one window.

Frame

PageWindow

Page 5: 03   page navigation and data binding in windows runtime apps

The Frame and the Navigation BackStack

The Frame is created on app launch

Frame acts as the container for Pages

It maintains a navigation history as you navigate through pagesFrame.BackStack property, returns an IList<PageStackEntry>

protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame;

// Do not repeat app initialization when the Window already has // content, just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate // to the first page rootFrame = new Frame();

...

// Place the frame in the current Window Window.Current.Content = rootFrame; }

if (rootFrame.Content == null) { // Navigate to the first page rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); }

Page 6: 03   page navigation and data binding in windows runtime apps

Navigation between pages

private void itemListView_ItemClick(object sender, ItemClickEventArgs e) { // Navigate to the appropriate destination page, configuring the new page

// by passing required information as a navigation parameter var itemId = ((MyListViewItem)e.ClickedItem).UniqueId; Frame.Navigate(typeof(MyDetailPage), itemId); }

You are responsible for contextWhen navigating to a page, you are responsible for providing any parameters/data using the “parameter” parameter of the Navigate method.

Page 7: 03   page navigation and data binding in windows runtime apps

Navigating BackApplication can execute logic to navigate back to preceding page

private void btnGoBack_Click( object sender, RoutedEventArgs e) { if (this.Frame.CanGoBack) this.Frame.GoBack(); }

Page 8: 03   page navigation and data binding in windows runtime apps

Navigation Bar Back KeyStandard Windows Phone UX is to use Back key to navigate back or close transient UIBy default, Back key causes a navigation back to the previous App – not Page!In Windows Phone Store apps, you must include code to override this to cause a backwards navigation within the appDiffers from Windows Phone Silverlight – within an app, backwards page navigation is default for that framework

With correct Back key handling, pressing the Back key on the launch page suspends the current app and navigates back to previous appDiffers from Windows Phone Silverlight – Closes the current app in that framework

Page 9: 03   page navigation and data binding in windows runtime apps

Back Key handling

New Project templates:Blank App does not include Back key handlingHub App, Pivot App does Included in /Common/NavigationHelper classCauses a backwards Page navigationIf you need to override this, replace with your own code for custom navigation handling

Page 10: 03   page navigation and data binding in windows runtime apps

Overriding the Back Key on a Page public sealed partial class SecondPage : Page { ...

protected override void OnNavigatedTo(NavigationEventArgs e) { Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed; }

protected override void OnNavigatedFrom(NavigationEventArgs e) { Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed; }

async void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e) { e.Handled = true; // We've handled this button press // If the secondary UI is visible, hide it if (SecondaryUI.Visibility == Visibility.Visible ) { FadeOutSecondaryStoryboard.Begin(); } else { // Standard page backward navigation if (Frame.CanGoBack) Frame.GoBack(); } }

Page 11: 03   page navigation and data binding in windows runtime apps

Navigation

demo

Page 12: 03   page navigation and data binding in windows runtime apps

Page Cache ModeWhen you navigate to a Page type the first time, a new instance is created.Whether that instance is cached or destroyed when you navigate away is determined by the NavigationCacheMode property of the Page

NavigationCacheMode.DisabledYou get a new instance of the page whether you navigate forward or backward to the page

NavigationCacheMode.EnabledThe page is cached, but the cached instance is discarded when the size of the cache for the frame is exceeded (determined by Frame.CacheSize property – default on Windows Phone is 10).

NavigationCacheMode.RequiredThe page is cached and the cached instance is reused for every visit regardless of the cache size for the frame

Page 13: 03   page navigation and data binding in windows runtime apps

Page cache mode

demo

Page 14: 03   page navigation and data binding in windows runtime apps

Saving and Restoring Page State on NavigationCommon scenario: User navigates to a Page that allows data entry. On first visit, the page is new, no data entered.The user interacts with the page, fills in some data. They navigate forward to another page for some purpose, then navigate back.

They expect the page to be in the same state as when they left it.With NavigationCacheMode.Disabled, a new instance is created when navigating back – original page state is lost.With NavigationCacheMode.Enabled or Required, cached page is re-used so original page state is retained. But it’s also still there on a forward navigation to the same page type in the future.

Page 1

Page 2

Page 3

new

new

?

Page 15: 03   page navigation and data binding in windows runtime apps

Navigation overrides

OnNavigatedToCalled when the user navigates to this pageLoad data, populate fields, wire-up event handlers, etc.

OnNavigatedFromCalled when this page is no longer active in the frame, typically when a user navigates awayDo any tear-down in this method

Page 16: 03   page navigation and data binding in windows runtime apps

Using NavigationHelper to Save/Restore Page StateIn your project, use ‘Add New Item…’ to add a Basic PageAdds a number of common helper classes to your project, including NavigationHelper

The code-behind of the new page shows the code you must add to any page where you want to use NavigationHelperInitialize in Page constructorCall helper methods in OnNavigatedTo/OnNavigatedFromWrite code to save Page state in NavigationHelper SaveState event handler, load state in LoadState handler

Gives the required behaviour: • Empty page on Forward (‘New’) navigation• Reloads page state on backward in navigation

Page 17: 03   page navigation and data binding in windows runtime apps

Saving and Restoring Page State with NavigationHelperdemo

Page 18: 03   page navigation and data binding in windows runtime apps

Data binding

Page 19: 03   page navigation and data binding in windows runtime apps

Data binding

Simplest way to program UI controls is to write your own “glue” to get and set properties of controlse.g. , textBox1.Text = "Hello, world";

In complex applications, such code quickly becomes unwieldy and error proneUse XAML data binding to link your UI to a class in your application that contains your application dataA class that is a source for data binding is called a ViewModelUI controls can get their display values automatically from properties of the viewmodel classChanging the property can update the displayUser input can automatically update the bound property of the viewmodel class

Page 20: 03   page navigation and data binding in windows runtime apps

Data binding in XAML

Properties of controls can be bound to a public property of a data objectIn the example above, the Text property of the TextBlock is bound to the Directions property of some data source

Define the data source by settingThe DataContext property of any FrameworkElement-derived class (can be set directly on the control, but often set on a containing control, such as a Grid, or on the page),

OrThe ItemsSource property of a List control

<TextBlock x:Name="DirectionsTextBlock" TextWrapping="Wrap" Margin="12,0,0,0" Text="{Binding Directions}" />

Page 21: 03   page navigation and data binding in windows runtime apps

Data binding modes

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 ignoredOneWay – Changes in the data object are synchronized to the control property, but changes in the control are not synchronized back to the data objectTwoWay – Changes in the data object are synchronized to the control property and vice-versa

<TextBlock x:Name="DirectionsTextBlock" TextWrapping="Wrap" Margin="12,0,0,0" Text="{Binding Directions, Mode=OneWay}" />

Page 22: 03   page navigation and data binding in windows runtime apps

INotifyPropertyChanged

Objects that take part in OneWay or TwoWay binding must implement the INotifyPropertyChanged interfaceThis interface requires only that the object publishes the PropertyChanged event

Object must fire the PropertyChanged event whenever the value of one of its public properties changesThe XAML runtime subscribes to this event and uses it to update databound UI elements

public class ItemViewModel : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged;…}

Page 23: 03   page navigation and data binding in windows runtime apps

How data binding works

ViewMyPage.xaml

ViewModelMyViewModel : INotifyPropertyChanged

PropertyChanged

<MyPage DataContext=MyViewModel >

Subscribes to

<TextBlock Text=“{Binding PropA}”/>

PropA: value XYZPropB: value 123

XYZ

PropA: value ABCPropB: value 123

ABC

Page 24: 03   page navigation and data binding in windows runtime apps

Non-Optimal ViewModel ImplementationError-prone because of use of ‘magic strings’ public class ItemViewModel : INotifyPropertyChanged { private string _id; /// Sample ViewModel property; public string ID { get { return _id; } set { if (value != _id) { _id = value; NotifyPropertyChanged("ID"); } } }

public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) handler(this, new PropertyChangedEventArgs(propertyName)); } }

Page 25: 03   page navigation and data binding in windows runtime apps

Optimal ViewModel Implementation public class ItemViewModel : INotifyPropertyChanged { // Properties private string _id; public string ID { get { return _id; } set { this.SetProperty(ref this._id, value); } }

// Property Change logic public event PropertyChangedEventHandler PropertyChanged; protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null) { if (object.Equals(storage, value)) return false; storage = value; this.OnPropertyChanged(propertyName); return true; }

protected void OnPropertyChanged([CallerMemberName] string propertyName = null) { var eventHandler = this.PropertyChanged; if (eventHandler != null) eventHandler(this, new PropertyChangedEventArgs(propertyName)); } }

Page 26: 03   page navigation and data binding in windows runtime apps

Binding to Lists

List controls can bind to collections of itemsSet the ItemsSource property to a collection of data objectsIn this example, the DataContext is a RecipeViewModel object, and the ItemsSource is bound to a property of that object called Ingredients that exposes a collection of objects

The ItemsSource can be bound to any collection class e.g. a List<T>But if you want your UI to update when items are added/removed, this should be an ObservableCollection<T> (implements INotifyCollectionChanged)Items inside the collection need to implement INotifyPropertyChanged

<ListView x:Name="IngredientsLIstBox" ItemTemplate="{StaticResource MyDataTemplate}" DataContext="{StaticResource RecipeViewModel}"/> ItemsSource="{Binding Ingredients}"/>

Page 27: 03   page navigation and data binding in windows runtime apps

Observable Collections

public class RecipeDetails : INotifyPropertyChanged { /// <summary> /// A collection for ItemViewModel objects. /// </summary> public ObservableCollection<ItemViewModel> Items { get; private set; }

public void LoadData() { this.Items.Add(new ItemViewModel() { ID = "0", LineOne = "runtime one", LineTwo = ... }); this.Items.Add(new ItemViewModel() { ID = "1", LineOne = "runtime two", LineTwo = ... }); this.Items.Add(new ItemViewModel() { ID = "2", LineOne = "runtime three", LineTwo =...}); } ...}

Page 28: 03   page navigation and data binding in windows runtime apps

Data binding Improvements:FallBackValue and TargetNullValue

Enhancements to XAML data binding introduced with Windows 8.1TargetNullValue allows you to specify an alternative property or value to display when the property you are bound to returns null

FallbackValue allows you to specify an alternative property or value to display when the property you are bound to does not exist

 <Button Content="{Binding Path=NextItem, Mode=OneWay, TargetNullValue={Binding Path=NullValue}}" />

 

<TextBlock Text="{Binding Path=badPath, FallbackValue='this is a fallback value'}" Grid.Column="1"> </TextBlock>

Page 29: 03   page navigation and data binding in windows runtime apps

MVVMMVVM stands for Model – View – ViewModelMVVM is an architectural pattern that employs Databinding and strict separation of concernsModel – a class or classes that exposes the data of your application, either fetched from local data storage or externally such as a web serviceViewModel – a class or classes that has properties and methods that can be used to databind to a ViewView – a class or classes that implement the presentation functionality of your application, displaying data and accepting user input. A View should contain no business logic, only logic pertaining to views such as that controlling the presentation. A view is bound to a ViewModel class.

SeeUsing the Model-View-ViewModel Pattern: MSDN http://msdn.microsoft.com/en-us/library/hh821028.aspx

Page 30: 03   page navigation and data binding in windows runtime apps

Databinding

demo

Page 31: 03   page navigation and data binding in windows runtime apps

Design-time Data

Page 32: 03   page navigation and data binding in windows runtime apps

Using Design-time data in XAML

Use d: namespace to define DataContext for design-time onlyCode your own design-time data classes in your projectOr use Blend to generate design-time data from your ViewModel classes

Page 33: 03   page navigation and data binding in windows runtime apps

Generating Design-Time Data in Blend

Design-time data is essential for designers to get the full benefits of WYSIWYG designing

Blend allows you to create sample data, to import it from XML or generate it from an existing class

Page 34: 03   page navigation and data binding in windows runtime apps

Can manually create data classes to be used at design time, but the easiest way is to define your data class in Visual Studio

Use ‘Create Sample Data from Class’ feature in Blend to generate the design-time data

Creating Sample Data From Class

Page 35: 03   page navigation and data binding in windows runtime apps

Edit Design-Time Data Format and Values

Easily edit the number of words Blend generates for each string field

Edit the maximum length of each word

Edit the format of the generated data

Page 36: 03   page navigation and data binding in windows runtime apps

Edit Design-Time Data Format and Values

Edit the sample data XML file that Blend generates

Page 37: 03   page navigation and data binding in windows runtime apps

Design-time Data

demo

Page 38: 03   page navigation and data binding in 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.