Upload
others
View
15
Download
0
Embed Size (px)
Citation preview
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 1
1
NE.15Data Binding In Windows Presentation Foundation
Brian NoyesChief ArchitectIDesign Inc (www.idesign.net)
2
About Brian• Chief Architect, IDesign Inc. (www.idesign.net) • Microsoft Regional Director/MVP• Writing
– Developing Applications with Windows Workflow Foundation, LiveLessons, June 2007
– Smart Client Deployment with ClickOnce, Addison-Wesley, Jan 2007– Data Binding in Windows Forms 2.0, Addison-Wesley, January 2006– MSDN Magazine, MSDN Online, CoDe Magazine, TheServerSide.NET,
asp.netPRO, Visual Studio Magazine• Speaking
– Microsoft TechEd, Visual Studio Connections, DevTeach, DevReach, INETA Speakers Bureau, MSDN Webcasts
• Participates in Microsoft Design Reviews• E-mail: [email protected]• Blog: http://briannoyes.net
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 2
3
Agenda• Data Sources for Data Binding• DataContext and Bindings• Collection Views and Data Providers• Data Templates• Value Conversion and Data Validation
4
Data Sources• Data binding data sources are always
objects in memory– Single objects– Collections of objects– DataSets
• Populating in memory data objects is not data binding– Data access
• WPF changes nothing about how to do data access in .NET– LINQ might
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 3
5
Data Binding Interfaces• Data binding in WPF (and Windows Forms)
is based on interfaces– IEnumerable
• Basic iteration pattern of .NET– IList
• Indexed, ordered collection– INotifyPropertyChanged
• Allows objects to notify when property values are changed– INotifyCollectionChanged
• Allows collections to notify when contained items change– ICollectionView
• Navigation, sorting, filtering, and grouping of items in a collection
6
Dependency Properties• New kind of property• Adds many semantics on top of simple .NET properties
– Value inheritance, animations, styling, data binding, etc.
• Defined on objects derived from DependencyObject• Have built in change notifications• Work seamlessly with WPF data binding• Consider exposing DependencyProperties for
all data bound properties
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 4
7
ObservableCollection<T>
• The collection of choice for data bound custom objects (entities)– Implements INotifyPropertyChanged and
INotifyCollectionChanged– Participates with 100% fidelity in WPF data
binding
8
Agenda• Data Sources for Data Binding• DataContext and Bindings• Collection Views and Data Providers• Data Templates• Value Conversion and Data Validation
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 5
9
Data Binding Overview• One-way data binding
– Taking data from an in-memory object and automatically presenting it through control properties on the screen
– Taking data from control and pushing it into an object
• Two-way data-binding– Both of the above
10
Data Binding In WPF• Rich infrastructure for binding control properties
to objects and collections• Loosely coupled model
– Control does not need to know anything about the type it is being bound to
• Can generate UI based on bound collections– Like ASP.NET
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 6
11
DataContext• Dependency property defined on FrameworkElement• Provides ambient data source for an
element and its children• May be set to a collection or an
individual object• Flows down the element hierarchy
to child elements• Picked up by bindings on child elements
12
Bindings• Tie a property on an object to a value
source for that property• Example
– Text property on TextBox• Pick up DataContext on element or parent
if set– DataContext knows current item if collection
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 7
13
Binding Properties• Path – property path on source object• Source – can set source object specifically by reference• RelativeSource – can set source object through relative path reference• ElementName – set to specific element in the element hierarchy by name• IsAsync – does the data binding asychronously from main UI rendering• Mode – allows you to specify one or two way data binding• Converter – specify a converter type that will be called to coerce values
14
Agenda• Data Sources for Data Binding• DataContext and Bindings• Collection Views and Data Providers• Data Templates• Value Conversion and Data Validation
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 8
15
Managing Bound Data• ICollectionView
– Defines API for managing data collection– Navigation– Sorting/Searching/Filtering/Grouping– Similar to IBindingList in Windows Forms
• CollectionViewSource– Obtain a collection view from a collection– Can wrap any IList or IListSource
• Ex: DataSet/DataTable
16
Data Providers• ObjectDataProvider
– Creates source object (with parameterized constructor)
– Point to a source method on object– ObjectType, MethodName properties
• XmlDataProvider– Bind to a chunk of XML– Source, XPath properties
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 9
17
Agenda• Data Sources for Data Binding• DataContext and Bindings• Collection Views and Data Providers• Data Templates• Value Conversion and Data Validation
18
Data Templates• Reusable chunks of XAML that can
be emitted during data binding• Can be defined through resources or
on control itself• Copy of template gets “spit out” by ItemsControl
derived class for each item in a data bound collection– Much like Repeater and DataList in ASP.NET
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 10
19
Agenda• Data Sources for Data Binding• DataContext and Bindings• Collection Views and Data Providers• Data Templates• Value Conversion and Data Validation
20
Value Conversion• Converter property on Binding, parameter
optional• Class that implements IValueConverter• Should put ValueConversion attribute on class[ValueConversion(typeof(Binary),typeof(byte[]))] public class BinaryToArrayConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { Binary bits = value as Binary; return (bits != null) ? bits.ToArray() : null; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 11
21
Data Validation• Two options
– Validation rules– IDataErrorInfo implementation on entity
(.NET 3.5 only)
22
Validation Rules
• Derive from ValidationRule class• Override Validate Method
public class AgeRule : ValidationRule{
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{if ((int)value < 18) return new ValidationResult(false, "Must be
older than 18");else return new ValidationResult(true, null);
}}
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 12
23
Validation Rules
• Add to Binding
<TextBox Name="ageTextBox"><TextBox.Text>
<Binding Path="Age"><Binding.ValidationRules>
<local:AgeRule /></Binding.ValidationRules>
</Binding></TextBox.Text>
</TextBox>
24
IDataErrorInfo• Implement IDataErrorInfo on entity class• Set error properties when validation
fails in property setters• Add DataErrorValidationRule to Binding.ValidationRules
or set ValidatesOnDataErrors property on Bindingpublic class SomeEntity : IDataErrorInfo{
public string Error {get;set;}
public string this[string columnName] {get;set;}
// Data members with validation in set blocks}
10/7/2008
Copyright © 2008 IDesign, Brian Noyes 13
25
Resources• WPF Unleashed, Adam Nathan, Sams Publishing,
www.adamnathan.net/wpf• Programming WPF 2nd Edition, Chris Sells and Ian Griffiths, O’Reilly
http://www.amazon.com/Programming-WPF-Chris-Sells/dp/0596510373
• Essential WPF, Chris Anderson, Addison Wesley, http://www.simplegeek.com/book
• .NET Rocks! TV: http://dnrtv.com (episodes 56,59, 101)• Data Binding with Windows Forms 2.0, Brian Noyes, Addison Wesley
http://www.softinsight.com/databindingbook
E-mail: [email protected]: http://briannoyes.net