Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "Ben Riga http://about.me/ben.riga 02 | Basics of View Models Ben Riga http://about.me/ben.riga."— Presentation transcript:

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

2 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

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

4 Data Binding Basics

5 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.

6 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.

7 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.

8 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

9 Data Binding: Under the Hood

10 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.

11 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.

12 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

13 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 ‘\’

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

15 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).

16 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.

17 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.

18 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.

19 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.

20 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.

21 Recap

22 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

23 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

24 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

25 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

26 Q&A

27


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

Similar presentations


Ads by Google