420 likes | 685 Views
Data Binding. In Windows 8 Store Applications. Doncho Minkov. Telerik Software Academy. http://academy.telerik.com. Senior Technical Trainer. http://minkov.it. Table of Contents. Data Binding Concepts Simple Data Binding List Data Binding Look-up bindings INotifyPropertyChanged
E N D
Data Binding In Windows 8 Store Applications Doncho Minkov Telerik Software Academy http://academy.telerik.com Senior Technical Trainer http://minkov.it
Table of Contents • Data Binding Concepts • Simple Data Binding • List Data Binding • Look-up bindings • INotifyPropertyChanged • Behavior Binding
Data Binding Concepts • Data binding is pulling information out of an object into another object or property • Data binding means automatically change the value of a property when the value of another property is changed • Many Windows applications are all about data • Data binding is a top concern in a user interface technologies like WPF, WinRT or SL • The XAML platform provides very powerful data binding mechanisms
Data Binding Start from the Simple stuff
Data Binding • Binding a property to a data source property: • The shorthand binding syntax: • Binding between the Text property of the TextBox and an object called PropertyName • PropertyNameis a property of some object to be named later <TextBox ...> <TextBox.Text> <Binding Path="PropertyName" /> </TextBox.Text> </TextBox> <TextBox Text="{Binding PropertyName}" />
Data Contexts • In XAML every FrameworkElement and every FrameworkContentElement has a DataContextproperty • DataContext is an object used as data source during the binding, addressed by binding Path • If you don’t specify a Source property • The XAML binding engine goes up the element tree in searching of a DataContext
Data Contexts (2) • Two controls with the same logical parent can bind to the same data source • Providing a DataContext value for both of the text box controls <!-- AppPage.xaml --> <Grid Name="GridMain"> … <TextBlock …>Name: </TextBlock> <TextBox Text="{Binding Path=Name}" … /> <TextBlock …>Vendor:</TextBlock> <TextBox Text="{Binding Path=Vendor}" … /> <Button Content="Purchase!" … /> </Grid>
Data Contexts (3) • Setting an object as a value of the grid’s DataContext property in the AppPage constructor: public partial class AppPage : Page { Game game = new Game("StarCraft", "Blizzard"); public AppPage() { InitializeComponent(); GridMain.DataContext = game; } … }
Data Contexts Live Demo
List Data Binding • Windows 8 Store apps support a range of controls, used to visualize collections of data • GridView, ListView, ComboBox, ItemsControl, ListBox, etc… • Binding to items controls is done pretty much the same as to regular controls • Instead of binding the Text property, bind the ItemsSource property
List Data Binding • Binding a ComboBox to a collection of data: <ListViewItemsSource="{Binding Games}" DisplayMemberPath="Name"/> public class AppViewModel { public IEnumerable<GameViewModel> Games { get; set; } } ViewModel • Set either the DisplayMemberPath View • Or the ItemTemplate View <ListViewItemsSource="{Binding Games}"> <ListView.ItemTemplate> … </ListView.ItemTemplate> </ListView>
List Data Binding Live Demo
Observable Collections • Items controls bind easily to collection of data • Yet changes to the collection does not reflect to the binding • Nothing alerts the data binding engine about changes in the ViewModel • Observable collection do the trick • An observable collection has a "update" event • The data binding engine registers for the event • Any change to the collection raises the event
Observable Collections: Sample • Use ObservableCollection<T> field • Expose IEnumerable<T> public property: public class AppViewModel { private ObservableCollection<GameViewModel> games; public IEnumerable<GameViewModel> Games { get { return this.games; } set {this.games = value; } } }
Observable Collections Live Demo
Look-up Bindings • Look-up bindings provide a way to bind elements to each other • Bind a game's vendor to the selected item from a ComboBox <TextBox Text="{Binding Path=NewGame.Name, Mode=TwoWay}" <ComboBoxItemsSource="{Binding Vendors}" SelectedItem="{Binding Path=NewGame.Vendor, Mode=TwoWay}"/>
INotifyProperyChanged • The INotifyPropertyChangedinterface introduces an event to notify about changes • The PropertyChanged event • The View attaches to the PropertyChanged event • When the ViewModel calls PropertyChanged, the View knows to update its bindings
INotifyProperyChanged (2) • The INotifyPropertyChangedinterface contains only one event PropertyChanged(object sender, PropertyChangedEventArgs e) • The point of this event is to be called when the data is changed • Both Model and ViewModel should implement this interface • In small project only the ViewModel can implement it
Implementing INotifyPropertyChanged • The View automatically subscribes for the PropertyChangedevent public class ViewModelBase: INotifyPropertyChanged { PropertyChanged(object sender,PropertyChangedEventArgs e) OnPropertyChanged(string propertyName) { if(this.PropertyChanged!=null) { varargs=new PropertyChangedEventArgs(propertyName); PropertyChanged(this, args); } } }
INotifyPropertyChanged Live Demo
Behavior Binding Abstracting the behavior of a ViewModel
Behavior Binding • WPF, Silverlight and WinRT does not provide a way to bind an event to a method in a DataContext/ViewModel • No way to bind the Click event to a method • All events are handled in the Code-behind • Handling of events in the code-behind is not the XAML way • Events somehow need to be handled in the ViewModel/DataContext
Behavior Binding • XAML does not provide a way to bind an event to a behavior(method) in the DataContext • Yet it does provide a way to bind to a property of the context • The behavior need to be abstracted into an object • Here comes the Command Design Pattern
The Command Design Pattern Abstract behavior into objects
The Command Design Pattern • The Command Design Pattern wraps behavior into a Command Object • Commands have method Execute, that invokes the given behavior • In WPF, SL or WinRT, just implement the ICommand interface • The ICommand interface provides: • Execute() method • CanExecute() method • CanExecuteChangedEventHandler
ICommand Members • ICommand has the following members: • Method Execute() • Invokes the abstracted behavior • Method CanExecute() • Validates if the command can be invoked
ICommand Implementation • Two common ways to implement Icommand • Create an inheritor for every command needed • This is kinds of hard, time consuming and can escalate to spaghetti code • Create a single implementation that gets its behavior • Something like a "generic" command • Gets its behavior from the constructor • The so called Relay/Delegate Command
The Delegate Command • The DelegateCommand contains a behavior passed into creation //in PhonesStoreViewModel.cs public ICommand Next { if(this.nextCommand == null) { this.nextCommand = new DelegateCommand(()=>{ …}); // new DelegateCommand(this.HandleNextCommand); } return this.nextCommand; } • Since now the behavior is wrapped in a object, the View can bind to it
DelegateCommand Live Demo
Data Binding http://academy.telerik.com
Homework • Develop a Windows 8 Store application for the game Tic-Tac-Toe • Use the MVVM design pattern • Use data and behavior binding • Develop a Windows 8 Store application for trivia. When the users starts a game, they get exactly 10 questions. The user can choose to get questions for a particular category, or from all categories • Each question have a single correct answer and many wrong answers • Questions are stored in an XML file