430 likes | 575 Views
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:
E N D
WPF Databinding Deep Dive Gill Cleeren Microsoft Regional Director – MVP ASP.NETOrdina .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: • TechDays • Usergroups(Visug, Biwug, Besug) • Ineta speaker • Blog: www.snowball.be • Email: gill.cleeren@ordina.be • Twitter: gillcleeren • MSN: gillcleeren@hotmail.com
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
Demo TechDays 2009 easiest demo
Conclusion of demo • Lots of code • Not easy to maintain and scale to many properties • Feels tedious to write
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
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
Demo - reprise TechDays 2009 easiest demoNow with databinding!
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
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...?
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
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
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
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
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
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
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
Demo Binding object Binding in XAML DataContext OneWay, TwoWay bindings
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
Collections YDatabinding • Important properties • DisplayMemberPath • SelectedValuePath • Customization via • Data Templates • ICollectionView
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
Data triggers • Can be used in combination with DataTemplates • Change value of property when property of object is certain value
Demo Databound collections DataTemplates DataTriggers
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
Demo Value conversion – Before and after...
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
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
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
Demo Sorting Grouping Filtering
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
Validation: ExceptionValidationRule <Binding Path="Salary" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding> • Built-in validation rule • Checks for errors thrown in update process
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
Demo Validation
Data providers • Generic databinding-friendly way to expose common items • 2 types • ObjectDataProvider • XmlDataProvider
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
ObjectDataProvider • Opens .NET object for databinding • ...? • Extra options • Object can be declared in XAML • Even with parameters • Bind to methods • Async options
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
Demo XmlDataProvider
Summary • Databinding reduces code written • Strongly customizable • Not always that easy when it comes to syntax
Resources • WPF Unleashed • Programming WPF, 2nd edition • MSDN Library
Q&A Did you understand everything...?
Thank you WPF Databinding Deep Dive Gill Cleeren Microsoft Regional Director – MVP ASP.NETOrdina .NET Architect gill.cleeren@ordina.be