wpf databinding deep dive

43
WPF Databinding Deep Dive Gill Cleeren Microsoft Regional Director – MVP ASP.NET Ordina .NET Architect [email protected]

Upload: livia

Post on 11-Feb-2016

59 views

Category:

Documents


1 download

DESCRIPTION

WPF Databinding Deep Dive. Gill Cleeren Microsoft Regional Director – MVP ASP.NET Ordina .NET Architect [email protected]. About Gill. .net architect Ordina (www.ordina.be) Microsoft Regional Director (www.theregion.com) MVP ASP.net Writing: .net magazine Blogs MSDN Speaking: - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: WPF Databinding Deep Dive

WPF Databinding Deep DiveGill CleerenMicrosoft Regional Director – MVP ASP.NETOrdina .NET [email protected]

Page 2: WPF Databinding Deep Dive

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: [email protected]• Twitter: gillcleeren • MSN: [email protected]

Page 3: WPF Databinding Deep Dive

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

Page 4: WPF Databinding Deep Dive

DemoTechDays 2009 easiest demo

Page 5: WPF Databinding Deep Dive

Conclusion of demo• Lots of code• Not easy to maintain and scale to

many properties• Feels tedious to write

Page 6: WPF Databinding Deep Dive

Hello databinding• Infrastructure for binding control properties to

objects and collectionsIt’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

Page 7: WPF Databinding Deep Dive

Welcome to databindingInfrastructure 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 toCan generate UI based on bound collectionsDatabinding isn’t unique to WPF

• ASP.NET• Windows Forms

Cp

Object

PropertyConversion

SynchronizationDependenc

y property

Control Data binding

Registration of property with databinding engine.Engine will keep them synchronized and take care of converion.

Page 8: WPF Databinding Deep Dive

Demo - repriseTechDays 2009 easiest demo

Now with databinding!

Page 9: WPF Databinding Deep Dive

The Binding object• System.Windows.Data.Binding• Glues 2 properties together

<TextBlock x:Name="currentFolder" DockPanel.Dock="Top"Background="AliceBlue" FontSize="16" />

void treeView_SelectedItemChanged(object sender,RoutedPropertyChangedEventArgs<object> e){ currentFolder.Text = (treeView.SelectedItem as TreeViewItem).Header.ToString(); Refresh();}

public MainWindow(){ InitializeComponent(); Binding binding = new Binding(); binding.Source = treeView; binding.Path = new PropertyPath(“SelectedItem.Header”); currentFolder.SetBinding(TextBlock.TextProperty, binding);}

Page 10: WPF Databinding Deep Dive

The Binding object• Binding has a• Source• Target

• SetBinding creates link with Target dependency property

• Alternative:

• How about XAML...?

BindingOperations.SetBinding(currentFolder, TextBlock.TextProperty, binding);

Page 11: WPF Databinding Deep Dive

Binding in XAML• More interesting to databind from

XAML

• Some important properties you need to know

<TextBlock x:Name="currentFolder" DockPanel.Dock="Top"Text="{Binding ElementName=treeView, Path=SelectedItem.Header} "Background="AliceBlue" FontSize="16" />

Property name FunctionElementName Source to update from is a

UIElementMode Type of binding: TwoWay, OneWay,

OneTime, OneWayToSourcePath Path to data on source objectSource Reference to the data to use as

source

Page 12: WPF Databinding Deep Dive

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

Page 13: WPF Databinding Deep Dive

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

Page 14: WPF Databinding Deep Dive

Binding to CLR objects (ie. Not DPs)

• 2 “issues”:• Requires a resource in XAML (files

collection)• Doesn’t have built-in plumbing for

change notification• INotifyPropertyChanged• INotifyCollectionChanged

• ObservableCollection

<Label x:Name=“countLabel"Content="{Binding Source={StaticResource files}, Path=Count}"DockPanel.Dock="Bottom"/>

Page 15: WPF Databinding Deep Dive

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

Page 16: WPF Databinding Deep Dive

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

Page 17: WPF Databinding Deep Dive

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

Page 18: WPF Databinding Deep Dive

DemoBinding objectBinding in XAMLDataContextOneWay, TwoWay bindings

Page 19: WPF Databinding Deep Dive

Collections YDatabinding• 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

<ListBox x:Name=”lstFiles”ItemsSource=”{Binding Source={StaticResource files}}” …></ListBox>

Page 20: WPF Databinding Deep Dive

Collections YDatabinding• Important properties• DisplayMemberPath• SelectedValuePath

• Customization via• Data Templates• ICollectionView

Page 21: WPF Databinding Deep Dive

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

Page 22: WPF Databinding Deep Dive

DataTemplates

Page 23: WPF Databinding Deep Dive

Data triggers• Can be used in combination with

DataTemplates• Change value of property when

property of object is certain value

Page 24: WPF Databinding Deep Dive

DemoDatabound collectionsDataTemplatesDataTriggers

Page 25: WPF Databinding Deep Dive

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

Page 26: WPF Databinding Deep Dive

DemoValue conversion – Before and after...

Page 27: WPF Databinding Deep Dive

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

Page 28: WPF Databinding Deep Dive

Let’s look at Sorting...• SortDescriptions property on

ICollectionView• Is a collection itselfview.SortDescriptions.Add(new SortDescription(“DateTime”,ListSortDirection.Descending));view.SortDescriptions.Add(new SortDescription(“Name”,ListSortDirection.Ascending));

Page 29: WPF Databinding Deep Dive

And then there was Grouping...• Allows to group items in groups and

possibly subgroups

• Needs GroupStyle on ItemsControl to be set

ICollectionView view = CollectionViewSource.GetDefaultView(this.FindResource(“photos”));view.GroupDescriptions.Clear();view.GroupDescriptions.Add(new PropertyGroupDescription(“DateTime”));

Page 30: WPF Databinding Deep Dive

DemoSortingGrouping Filtering

Page 31: WPF Databinding Deep Dive

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

Page 32: WPF Databinding Deep Dive

Validation: ExceptionValidationRule

• Built-in validation rule• Checks for errors thrown in update

process

<Binding Path="Salary" UpdateSourceTrigger="PropertyChanged"> <Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules> </Binding>

Page 33: WPF Databinding Deep Dive

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

Page 34: WPF Databinding Deep Dive

DemoValidation

Page 35: WPF Databinding Deep Dive

Data providers• Generic databinding-friendly way to

expose common items• 2 types• ObjectDataProvider• XmlDataProvider

Page 36: WPF Databinding Deep Dive

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

Page 37: WPF Databinding Deep Dive

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

Page 38: WPF Databinding Deep Dive

ObjectDataProvider• Instantiate on demand

• Instantiate with parameters

• Bind to method

<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"/>

Page 39: WPF Databinding Deep Dive

DemoXmlDataProvider

Page 40: WPF Databinding Deep Dive

Summary• Databinding reduces code written• Strongly customizable• Not always that easy when it comes

to syntax

Page 41: WPF Databinding Deep Dive

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

Page 42: WPF Databinding Deep Dive

Q&A

Did you understand everything...?

Page 43: WPF Databinding Deep Dive

WPF Databinding Deep DiveGill CleerenMicrosoft Regional Director – MVP ASP.NETOrdina .NET [email protected]

Thank you