1 / 43

WPF Databinding Deep Dive

WPF Databinding Deep Dive. Gill Cleeren Microsoft Regional Director – MVP ASP.NET Ordina .NET Architect gill.cleeren@ordina.be. About Gill. .net architect Ordina (www.ordina.be) Microsoft Regional Director (www.theregion.com) MVP ASP.net Writing: .net magazine Blogs MSDN Speaking:

livia
Download Presentation

WPF Databinding Deep Dive

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. WPF Databinding Deep Dive Gill Cleeren Microsoft Regional Director – MVP ASP.NETOrdina .NET Architect gill.cleeren@ordina.be

  2. About Gill • .net architect Ordina (www.ordina.be) • Microsoft Regional Director (www.theregion.com) • MVP ASP.net • Writing: • .net magazine • Blogs • MSDN • Speaking: • TechDays • Usergroups(Visug, Biwug, Besug) • Ineta speaker • Blog: www.snowball.be • Email: gill.cleeren@ordina.be • Twitter: gillcleeren • MSN: gillcleeren@hotmail.com

  3. Agenda • From manual coding to databinding • The Binding object • Types of Binding and the DataContext • Collections binding and datatemplates • Value conversions • Customizations of the view • Validation • Data providers

  4. Demo TechDays 2009 easiest demo

  5. Conclusion of demo • Lots of code • Not easy to maintain and scale to many properties • Feels tedious to write

  6. Hello databinding • Infrastructure for binding control properties to objects and collections It’s like saying: “Hey ListBox, get your items here.”“And keep them up-to-date please.”“Oh and format them like this...”And much more, all automagically! • Loosely coupled model • Bound control doesn’t need to know to what is being bound to • Databinding isn’t unique to WPF • ASP.NET • Windows Forms

  7. Welcome to databinding Cp Control Data binding Object Synchronization Dependency property Property Conversion Registration of property with databinding engine. Engine will keep them synchronized and take care of converion. • Infrastructure for binding control properties to objects and collections • It’s like saying: “Hey ListBox, get your items here.”“And keep them up-to-date please.”“Oh and format them like this...”And much more, all automagically! • Loosely coupled model • Bound control doesn’t need to know to what is being bound to • Can generate UI based on bound collections • Databinding isn’t unique to WPF • ASP.NET • Windows Forms

  8. Demo - reprise TechDays 2009 easiest demoNow with databinding!

  9. The Binding object <TextBlock x:Name="currentFolder" DockPanel.Dock="Top" Background="AliceBlue" FontSize="16" /> public MainWindow() { InitializeComponent(); Binding binding = new Binding(); binding.Source = treeView; binding.Path = new PropertyPath(“SelectedItem.Header”); currentFolder.SetBinding(TextBlock.TextProperty, binding); } void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e) { currentFolder.Text = (treeView.SelectedItem as TreeViewItem).Header.ToString(); Refresh(); } • System.Windows.Data.Binding • Glues 2 properties together

  10. The Binding object BindingOperations.SetBinding (currentFolder, TextBlock.TextProperty, binding); • Binding has a • Source • Target • SetBinding creates link with Target dependency property • Alternative: • How about XAML...?

  11. Binding in XAML <TextBlock x:Name="currentFolder" DockPanel.Dock="Top" Text="{Binding ElementName=treeView, Path=SelectedItem.Header} " Background="AliceBlue" FontSize="16" /> • More interesting to databind from XAML • Some important properties you need to know

  12. What data can we bind? • Data sources for databinding need to be in-memory objects • Single objects • Collection of objects... • How the objects get there, has nothing to do with databinding • Pure data-access

  13. DependencyProperty: a sidestep • New type of Property • Adds many semantics on top of simple .NET properties • Value inheritance, DataBinding, Styling, Animations... • Defined on objects derived from DependencyObject • Built-in change notification • Perfect for our DataBinding • Its value can rely on one or more sources (StoryBoard, Binding...) • DPs allow the previous kinds of Bindings

  14. Binding to CLR objects (ie. Not DPs) <Label x:Name=“countLabel" Content="{Binding Source={StaticResourcefiles}, Path=Count}" DockPanel.Dock="Bottom"/> • 2 “issues”: • Requires a resource in XAML (files collection) • Doesn’t have built-in plumbing for change notification • INotifyPropertyChanged • INotifyCollectionChanged • ObservableCollection

  15. Types of Binding • OneWay: Target updates when source changes • TwoWay: Change to either changes the other • OneTime: Similar to OneWay, changes aren’t reflected in Target (snapshot view) • OneWayToSource:Source updates when Target changes

  16. When do bindings update? • UpdateSourceTrigger • PropertyChanged: the source is updated when the target property value changes • LostFocus: the source is only updated after the target element loses focus (and the value changed) • Explicit: source is only updated when making an explicit call to BindingExpression.UpdateSource

  17. DataContext • Place for bindings to look for data source if nothing more specific is specified • A Profile form will often bind to a Profile object • DataContext should be specified on common parent element • Flows down on its child elements • Defined as DP on FrameworkElement • WPF traverses logical tree to find nonnull DataContext

  18. Demo Binding object Binding in XAML DataContext OneWay, TwoWay bindings

  19. Collections YDatabinding <ListBox x:Name=”lstFiles” ItemsSource=”{Binding Source={StaticResource files}}” …> </ListBox> • Binding an entire collection to a list control is similar • Don’t use *.Items property (not a DP), use ItemsSource • Source collection must implement INotifyCollectionChanged • ObservableCollection

  20. Collections YDatabinding • Important properties • DisplayMemberPath • SelectedValuePath • Customization via • Data Templates • ICollectionView

  21. DataTemplates • Piece of XAML to be applied to a .NET object when it is rendered • Swap in new visual tree for element • Can be defined in resources or on control itself • Many control have property of type DataTemplate • ItemsControl: ItemTemplate • Gets spit out for every item

  22. DataTemplates

  23. Data triggers • Can be used in combination with DataTemplates • Change value of property when property of object is certain value

  24. Demo Databound collections DataTemplates DataTriggers

  25. Value conversion • Morph source value in different target value • Plug in custom logic and still use databinding • Change TextBox border based on value of some field • Formatting values • Achieved using Converter property with optional parameter • Class implements IValueConverter and has ValueConversion attribute • Convert and ConvertBack method

  26. Demo Value conversion – Before and after...

  27. Further customization of the View • When binding, a view is inserted between source and target • Stores current item • Allows for sorting, grouping, filtering and navigation • Type is ICollectionView

  28. Let’s look at Sorting... view.SortDescriptions.Add(new SortDescription(“DateTime”, ListSortDirection.Descending)); view.SortDescriptions.Add(new SortDescription(“Name”, ListSortDirection.Ascending)); • SortDescriptions property on ICollectionView • Is a collection itself

  29. And then there was Grouping... ICollectionView view = CollectionViewSource.GetDefaultView( this.FindResource(“photos”)); view.GroupDescriptions.Clear(); view.GroupDescriptions.Add(new PropertyGroupDescription(“DateTime”)); • Allows to group items in groups and possibly subgroups • Needs GroupStyle on ItemsControl to be set

  30. Demo Sorting Grouping Filtering

  31. Validation • WPF Databinding has built-in validation • Confusing because of many options • Several options to do validation • ExceptionValidationRule • Custom validation rules • Binding has ValidationRules property • Validation follows a strict pattern

  32. Validation: ExceptionValidationRule <Binding Path="Salary" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> • Built-in validation rule • Checks for errors thrown in update process

  33. Validation: Custom rules • Derive from ValidationRule class and implement Validate method • Called on every attempt to update underlying data item • UIElement will be marked red (Can be overriden through Validation.ErrorTemplate) • Validation.HasError • Validation.Error event raised • Implement richer logic if needed

  34. Demo Validation

  35. Data providers • Generic databinding-friendly way to expose common items • 2 types • ObjectDataProvider • XmlDataProvider

  36. XmlDataProvider • Provides easy way to databind XML • Allows to bind to • Embedded XML • XML file (via Source property) • XmlDocument (via Document property) • XPath expression is used to extract data • Read-only access to XML • If more is needed, use other XML options

  37. ObjectDataProvider • Opens .NET object for databinding • ...? • Extra options • Object can be declared in XAML • Even with parameters • Bind to methods • Async options

  38. ObjectDataProvider <Window.Resources> <ObjectDataProvider x:Key=“myData" ObjectType="{x:Type my:Staff}"/> </Window.Resources> <ObjectDataProvider x:Key="myData" ObjectType="{x:Type my:Staff}"> <ObjectDataProvider.ConstructorParameters> <sys:Int32>23</sys:Int32> </ObjectDataProvider.ConstructorParameters> </ObjectDataProvider> <ObjectDataProvider x:Key="myData" ObjectType="{x:Type my:Staff}" MethodName="GetAllStaffMembers"/> • Instantiate on demand • Instantiate with parameters • Bind to method

  39. Demo XmlDataProvider

  40. Summary • Databinding reduces code written • Strongly customizable • Not always that easy when it comes to syntax

  41. Resources • WPF Unleashed • Programming WPF, 2nd edition • MSDN Library

  42. Q&A Did you understand everything...?

  43. Thank you WPF Databinding Deep Dive Gill Cleeren Microsoft Regional Director – MVP ASP.NETOrdina .NET Architect gill.cleeren@ordina.be

More Related