Presentation is loading. Please wait.

Presentation is loading. Please wait.

Page Navigation and Data Binding in Windows Runtime Apps

Similar presentations


Presentation on theme: "Page Navigation and Data Binding in Windows Runtime Apps"— Presentation transcript:

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

2 In this module… 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

3 1/14/2019 Page navigation © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

4 Windows, Frames and Pages
1/14/2019 Windows, Frames and Pages Window Window Frame Page 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. © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

5 The Frame and the Navigation BackStack
1/14/2019 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 pages Frame.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(); © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

6 Navigation between pages
1/14/2019 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 context When navigating to a page, you are responsible for providing any parameters/data using the “parameter” parameter of the Navigate method. © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

7 Navigating Back Application can execute logic to navigate back to preceding page private void btnGoBack_Click( object sender, RoutedEventArgs e) { if (this.Frame.CanGoBack) this.Frame.GoBack(); }

8 Navigation Bar Back Key
Standard Windows Phone UX is to use Back key to navigate back or close transient UI By 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 app Differs 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 app Differs from Windows Phone Silverlight – Closes the current app in that framework

9 Back Key handling New Project templates:
1/14/2019 Back Key handling New Project templates: Blank App does not include Back key handling Hub App, Pivot App does Included in /Common/NavigationHelper class Causes a backwards Page navigation If you need to override this, replace with your own code for custom navigation handling © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

10 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();

11 1/14/2019 Navigation demo © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

12 Page Cache Mode When 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.Disabled You get a new instance of the page whether you navigate forward or backward to the page NavigationCacheMode.Enabled The 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.Required The page is cached and the cached instance is reused for every visit regardless of the cache size for the frame

13 1/14/2019 Page cache mode demo © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

14 Saving and Restoring Page State on Navigation
Common 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. new Page 1 Page 2 new Page 3 ?

15 Navigation overrides OnNavigatedTo OnNavigatedFrom
1/14/2019 Navigation overrides OnNavigatedTo Called when the user navigates to this page Load data, populate fields, wire-up event handlers, etc. OnNavigatedFrom Called when this page is no longer active in the frame, typically when a user navigates away Do any tear-down in this method © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

16 Using NavigationHelper to Save/Restore Page State
1/14/2019 Using NavigationHelper to Save/Restore Page State In your project, use ‘Add New Item…’ to add a Basic Page Adds 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 NavigationHelper Initialize in Page constructor Call helper methods in OnNavigatedTo/OnNavigatedFrom Write 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 © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

17 Saving and Restoring Page State with NavigationHelper
1/14/2019 Saving and Restoring Page State with NavigationHelper demo © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

18 Data binding

19 1/14/2019 Data binding Simplest way to program UI controls is to write your own “glue” 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 UI to a class in your application that contains your application data A class that is a source for data binding is called a ViewModel UI controls can get their display values automatically from properties of the viewmodel class Changing the property can update the display User input can automatically update the bound property of the viewmodel class © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

20 Data binding in XAML <TextBlock x:Name="DirectionsTextBlock" TextWrapping="Wrap" Margin="12,0,0,0" Text="{Binding Directions}" /> 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 Directions property of some data source Define the data source by setting The 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), Or The ItemsSource property of a List control

21 Data binding modes <TextBlock x:Name="DirectionsTextBlock" TextWrapping="Wrap" Margin="12,0,0,0" Text="{Binding Directions, 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

22 INotifyPropertyChanged
Objects that take part in OneWay or TwoWay binding must implement the INotifyPropertyChanged interface This 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 changes The XAML runtime subscribes to this event and uses it to update databound UI elements public class ItemViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; }

23 How data binding works View MyPage.xaml ViewModel ABC XYZ
1/14/2019 How data binding works <MyPage DataContext=MyViewModel > View MyPage.xaml ViewModel MyViewModel : INotifyPropertyChanged Subscribes to PropertyChanged <TextBlock Text=“{Binding PropA}”/> PropA: value ABC PropB: value 123 PropA: value XYZ PropB: value 123 ABC XYZ © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

24 Non-Optimal ViewModel Implementation Error-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)); }

25 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));

26 Binding to Lists List controls can bind to collections of items
<ListView x:Name="IngredientsLIstBox" ItemTemplate="{StaticResource MyDataTemplate}" DataContext="{StaticResource RecipeViewModel}"/> ItemsSource="{Binding Ingredients}"/> List controls can bind to collections of items Set the ItemsSource property to a collection of data objects In 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

27 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 =...}); } ... }

28 Data binding Improvements: FallBackValue and TargetNullValue
1/14/2019 Data binding Improvements: FallBackValue and TargetNullValue Enhancements to XAML data binding introduced with Windows 8.1 TargetNullValue 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> © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

29 MVVM MVVM stands for Model – View – ViewModel
MVVM is an architectural pattern that employs Databinding and strict separation of concerns Model – a class or classes that exposes the data of your application, either fetched from local data storage or externally such as a web service ViewModel – a class or classes that has properties and methods that can be used to databind to a View View – 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. See Using the Model-View-ViewModel Pattern: MSDN

30 1/14/2019 Databinding demo © 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

31 Design-time Data

32 Using Design-time data in XAML
1/14/2019 Using Design-time data in XAML Use d: namespace to define DataContext for design-time only Code your own design-time data classes in your project Or use Blend to generate design-time data from your ViewModel classes © 2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

33 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

34 Creating Sample Data From Class
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

35 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

36 Edit Design-Time Data Format and Values
Edit the sample data XML file that Blend generates

37 Design-time Data demo 1/14/2019
© 2012 Microsoft Corporation. All rights reserved. Microsoft, Windows, 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.

38


Download ppt "Page Navigation and Data Binding in Windows Runtime Apps"

Similar presentations


Ads by Google