Ben Riga http://about.me/ben.riga 02 | Basics of View Models Ben Riga http://about.me/ben.riga.

Slides:



Advertisements
Similar presentations
MVVM Overview Frank Shoemaker MindCrafted Systems
Advertisements

An Introduction to the Model-View-ViewModel Pattern Srsly? Another MV* Pattern? Srsly? Another MV* Pattern?
Dinko Jakovljević Microsoft Student Partner | BambooLab
Or How I Learned to Stop Worrying and Love the Binding Bryan Anderson.
WinRT Apps
Web Development Using ASP.NET CA – 240 Kashif Jalal Welcome to week – 3-1 of…
Real world Windows Phone development Igor
Chapter 13: Advanced GUI and Graphics
Building Silverlight Applications Using the MVVM pattern An Introduction by Peter Messenger Senior Developer – Qmastor
.NET Database Technologies: Introduction to WPF and Entity Framework DataBinding.
Overview of Previous Lesson(s) Over View  ASP.NET Pages  Modular in nature and divided into the core sections  Page directives  Code Section  Page.
Chapter 6 Understanding the Structure of an Application: Procedures, Modules, and Classes.
An Introduction to Silverlight Matt Harrington Developer Evangelist, Microsoft October 20, 2011.
IE 411/511: Visual Programming for Industrial Applications
Virtual techdays INDIA │ Nov 2010 Developing Office Biz Application using WPF on Windows 7 Sarang Datye │ Sr. Consultant, Microsoft Sridhar Poduri.
LiveCycle Data Services Introduction Part 2. Part 2? This is the second in our series on LiveCycle Data Services. If you missed our first presentation,
Windows Presentation Foundation Adam Calderon Principal Engineer Interknowlogy LLC
Adam Calderon – C# MVP Application Development Practice Lead Interknowlogy.
V 1.0 Programming III. Automatic notifications (…Changed, INofityPropertyChanged, ObservableCollection ) Data formatters Data conversions Resources.
LAYOUT CONTROLS. XAML Overview XAML : eXtensible Application Markup Language pronounced (ZAMEL) is a markup language used to design user interfaces XML-based.
Object Oriented Software Development 9. Creating Graphical User Interfaces.
Windows Phone MVVM and Unit Testing Step by Step Andy Wigley Windows Phone Development MVP, Mobile Software Consultant APPA Mundi Ltd WPH208.
1 Chapter 12: Form Builder Objects and Flexible Code.
Module 7 Data Binding to Collections. Module Overview Binding to Collections of Objects Using Collection Views Create Master-Detail User Interfaces Using.
Windows Presentation Foundation (WPF). Introduction Separates appearance of user interface from behavior Appearance usually specified by XAML Behavior.
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
Graphical Enablement In this presentation… –What is graphical enablement? –Introduction to newlook dialogs and tools used to graphical enable System i.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Nikhil Kothari Software Architect Microsoft Corporation Session Code: WUX312.
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
1 Catching up on Rich Clients (round 1) Mike Ormond, Mike Taulty Developer & Platform Group Microsoft Ltd
Module 4 Taking Control of the User Interface. Module Overview Sharing Logical Resources in an Application Creating Consistent User Interfaces by Using.
Understanding Desktop Applications Lesson 5. Objective Domain Matrix Skills/ConceptsMTA Exam Objectives Understanding Windows Forms Applications Understand.
04 |Sharing Code Between Windows 8 and Windows Phone 8 in Visual Studio Ben Riga
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
V 1.0 Programming III. Automatic notifications with data binding (…Changed, INofityPropertyChanged, ObservableCollection, DataTemplate) Data formatters.
Understanding Desktop Applications Lesson 5. Understanding Windows Forms Applications Windows Forms applications are smart client applications consisting.
Model View ViewModel Architecture. MVVM Architecture components.
Copyright ©2004 Virtusa Corporation | CONFIDENTIAL Windows Presentation Foundation Ruwan Wijesinghe.
Windows 8 apps and the MVVM pattern SILVERLIGHTSHOW.NET WEBINARS SERIES GILL CLEEREN, October 16 th
Programming with MVVM Miguel A. Castro Architect -
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Data Binding, Binding Properties Doncho Minkov Telerik School Academy Technical Trainer
Adam Schultz MVVM and WPF. MVVM Model, View, ViewModel A software architecture designed to separate out User Interface design, Business Logic, and Data.
In Windows 8 Store Applications
Real world Windows Phone development
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Microsoft Foundation Classes MFC
Forms Concepts Triggers Fired when Internal/External events occur
Lesson # 9 HP UCMDB 8.0 Essentials
Working in the Forms Developer Environment
IS 350 Application Structure
Chapter 1: An Introduction to Visual Basic 2015
Chapter Topics 15.1 Graphical User Interfaces
Java Beans Sagun Dhakhwa.
Build Windows 10 UWP MVVM Apps with Prism
Jim Fawcett CSE775 – Distributed Objects Spring 2011
Introduction to Events
Hands-on Introduction to Visual Basic .NET
An introduction to MVVM using WPF NISCHAL S
Page Navigation and Data Binding in Windows Runtime Apps
Developing a Model-View-Controller Component for Joomla
Web Development Using ASP .NET
Chapter 15: GUI Applications & Event-Driven Programming
Model, View, Controller design pattern
MVC in AX2012 Rama Sridhar
Bringing existing managed code into Metro style apps
Data/Code driven UI using WPF part 2
Presentation transcript:

Ben Riga http://about.me/ben.riga 02 | Basics of View Models Ben Riga http://about.me/ben.riga

Course Topics Building Apps for Both Windows 8 and Windows Phone 8 Jump Start 01 | Comparing Windows 8 and Windows Phone 8 02 | Basics of View Models 03 | MVVM ( (Model-View-ViewModel) 04 | Sharing Code

Agenda Data binding basics Data binding: under the hood Q&A Dependency object, dependency property View Model INotifyPropertyChanged, INotifyCollectionChanged Commands Q&A

Data Binding Basics

Data Binding Overview Writing the code to synchronize a data model with a view can be difficult to maintain and test Could use a mechanism to help with this task Data binding lets you synchronize the data displayed in a view with a data source Without data binding, you may end up with overly-large and hard-to-maintain code behind files for your views. The XAML data binding engine performs the work of observing for changes and then synchronizing data between the source and the target.

Data Binding Overview Each data binding has three parts: Binding source: an object with data that you want to present (this is the View Model) Binding target: a DependencyProperty of a FrameworkElement Binding object: synchronizes data between the source and target, possibly reformatting it with a value converter Without data binding, you may end up with overly-large and hard-to-maintain code behind files for your views. The XAML data binding engine performs the work of observing for changes and then synchronizing data between the source and the target.

Data Binding Architecture Data Updates (one-way) Data Updates (one-way) Binding Source (DependecyProperty / INotifyPropertyChanged) Binding Object Binding Target (Property) Data Updates (two-way) Data Updates (two-way) Binding engine gets information from the Binding object: Source and target objects Direction of the data flow (Binding.Mode property) Optionally, a value converter (Converter property) Instance of a class that implements IValueConverter The binding engine, a part of Windows Runtime, is hidden from the developer. The binding object supplies the engine with information about the binding so that it can perform its duties. The engine observes changes in the binding source and target and updates data appropriately. The developer can provide an optional value converter that converts data between the source format and target format (the two boxes in the diagram are the same converter). Note that the binding engine updates data depending on the binding mode – one time, one way, or two way. A data class that is suitable for being a binding source is known as a View Model.

Data Binding Two ways in XAML to define the source object for a data binding: DataContext property Must bind to a type that implements INotifyPropertyChanged Sets the bindings for that element and all child elements ItemsSource property of a List control Must bind to a type that implements INotifyCollectionChanged ObservableCollection is a built-in class that implements this Items contained by the collection must implement INotifyPropertyChanged Some Visual Studio project templates create a BindableBase that is a useful abstract base class for your View Model objects

Data Binding: Under the Hood

Dependency Property, Dependency Object A DependencyProperty is a special type of property Can be data bound Tracked by XAML Binding Engine For data binding to work, the object with the dependency property must be a subclass of DependencyObject FrameworkElement is a subclass of DependencyObject, so all controls can participate in data binding <TextBlock x:Name="DescriptionTextBlock" Margin="12,0,0,0" Text="{Binding Description} " /> Dependency Object Dependency Property Binding Markup Extension The binding statement does not say exactly which data object (binding source) is used to supply the value. It just states that if this element is bound to a data object with a property called Directions, the Text property will be synchronized with that property. The default binding mode is one-way, meaning that changes to the data model will change the view, but not vice versa. This can be done by setting the binding Mode to two-way. You define the actual object to use for data binding by setting the DataContext property. You can set DataContext on an individual element, or on a containing element, in which case it is inherited by all the contained controls. You can simply set DataContext on a Grid or on the whole Page. Note that this is usually done from code when the page is navigated to.

Converters Converters let you bind a target and a source that are different types For example: suppose you want to show an element only if a bool variable is true Provide a class that implements IValueConverter Implement Convert that converts from the source type to the target type Implement ConvertBack that converts from the target type to the source type Implement these methods to create any mapping between two types. <TextBlock x:Name="MyTextBlock" Visibility="{Binding IsVisibleBool, Converter={StaticResource BoolToVisibilityConverter}}" /> The XAML code example shows a TextBlock with the Visibility property bound to IsVisibleBool (presumably defined in the DataContext object). Because the source and target types do not match, a class named BoolToVisibilityConverter is provided as a converter. That class should implement the IValueConverter interface and convert objects between bool and System.Windows.Visibility. We will see an example of a converter in the demo.

Binding Modes Binding Mode One-time: view is populated with data from the model only once, on page load One-way: view is changed to match the data from the model Two-way: data in the view and the model is synchronized so changes in one change the other <Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" Width="150" Stretch="UniformToFill" Grid.RowSpan="2" /> If you only bind with the OneTime Mode, the source object does not need to implement INotifyPropertyChanged. The WP8 Runtime just queries the property once and does not need to track it afterwards. Do not needlessly use two-way binding when one-way or even one-time binding would work

Other Binding Options More advanced property paths Instead of just setting the source to a property of the data context object, you can chain together properties to dig into the object: Use the StringFormat property to format text in data bindings The property being bound should implement the IFormattable interface (DateTime in this example) <Image Source="{Binding VisualElement.BackgroundImage, Mode=OneTime}" Width="150" Stretch="UniformToFill" Grid.RowSpan="2" /> <TextBlock Text="{Binding Coupon.ExpirationDate, StringFormat=Expiration Date: \{0:d\}}" Style="{StaticResource PhoneTextSmallStyle}" FontWeight="Bold" Foreground="{StaticResource CustomGroupTitleBrush}" Grid.Row="2" HorizontalAlignment="Center" VerticalAlignment="Stretch"/> We will see examples of advanced property paths and the StringFormat property in the demo. Extra info about StringFormat: The formatting is applied after any converters Escape special characters with a ‘\’

Demo 1: Data Binding Open “Demo_01_Data_Binding.docx” and follow the instructions.

View Model A class that acts as a binding source is considered a View Model Loosely coupled to a View Avoid direct references to individual XAML elements Exposes properties for binding Implements INotifyPropertyChanged and raises the PropertyChanged event whenever a property is set Include business logic to respond to user actions in the view Makes sure that changes to data are persisted Tells a data service to save changes XAML is one end of data binding, and the View Model is the other end. It essentially “presents” your app data to the view. A substantial part of your code should be in the View Model(s).

View Model Example public class ItemView Model : INotifyPropertyChanged { private string _name; public string Name { get { return _name; } set { if (value != _name) _name = value; NotifyPropertyChanged("Name"); } public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String propertyName) PropertyChangedEventHandler handler = PropertyChanged; if (null != handler) handler(this, new PropertyChangedEventArgs(propertyName)); In Windows 8, the [CallerMemberName] attribute is a new feature that lets you obtain the name of the method or property calling a method. It is used above to get the string name of the property being set (“Name” in this case), and can help avoid cluttering your code with constant strings to identify properties.

INotifyPropertyChanged Binding source objects (View Models) that are part of a OneWay or TwoWay binding must implement the INotifyPropertyChanged interface Fire the PropertyChanged event whenever the value of a public property changes The runtime framework subscribes to this event and uses it to update bound UI elements One time binding does not require this The INotifyPropertyChanged interface lets an object participate as a source in a one- way or two-way data binding. The interface exposes a single event, PropertyChanged. Classes that implement this interface should fire the PropertyChanged event whenever a public setter is called. The name of the property is passed in the PropertyChangedEventArgs.

Data Binding with Lists Can also bind to lists Two ways to bind collections of data: Extend ObservableCollection<T> Implement IList and INotifyCollectionChanged Items in the collection must implement INotifyPropertyChanged In the ItemsPanel of the XAML list element, you are bound to the individual item of the collection The INotifyPropertyChanged interface lets an object participate as a source in a one- way or two-way data binding. The interface exposes a single event, PropertyChanged. Classes that implement this interface should fire the PropertyChanged event whenever a public setter is called. The name of the property is passed in the PropertyChangedEventArgs.

Commands Let you expose a method like a property Can attach commands to buttons (of any type) and menu items Automatically executed by the system Lets the view notify the code that some action has occurred For example, when the user clicks a button, the app could clear a canvas or refresh data from a server Implement the ICommand interface Execute: code that runs when the command is invoked CanExecute: called to check if the command is enabled CanExecuteChanged: raise this event when a command is enabled/disabled Commands can involve a lot of boilerplate code, but a library can be helpful with this.

Commands Example <Button Content="Say Hello" Command="{Binding HelloWorldCommand}"></Button> protected override void OnNavigatedTo(NavigationEventArgs e) { DataContext = _myView Model; } class HelloWorldCommand : ICommand { public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter) return true; }   public void Execute(object parameter) MessageBox.Show("Hello world!"); class MyView Model { private HelloWorldCommand myCommand = new HelloWorldCommand(); public HelloWorldCommand HelloWorldCommand get return myCommand; } This is a very barebones implementation to get a command working, but it demonstrates the basic idea. The Command property of the Button is bound to a class that implements the ICommand interface.

Recap

Recap Binding greatly reduces the amount of code required to synchronize your app data with the data presented in the view Use a view model to present data to the view and update the model as necessary The XAML binding engine does most of the work for you

Recap (cont.) Use binding markup extensions to link properties of XAML elements to the source All XAML controls are FrameworkElement , which inherits DependencyObject Make sure to set the DataContext or the ItemsSource property when data binding Can do this from code after loading your data Implement the INotifyPropertyChanged interface in your binding source object

Recap (cont.) Use converters to bind different source and target types Properties in the binding property path can be chained together to dig into objects that are containers Decide which binding Mode (one-time, one-way, two-way) is best for each property

Recap (cont.) Use commands to run some code when the user interacts with an element, such as clicking a button. No event handling needed, system automatically invokes the method Can reuse commands to provide multiple ways to achieve the same thing in the UI

Q&A