Title: An%20Introduction%20to%20Data%20Binding%20in%20Windows%20Presentation%20Foundation%20(WPF)
1An Introduction to Data Binding in Windows
Presentation Foundation (WPF)
- Adam Calderon C MVP
- Application Development Practice Lead
- Interknowlogy
2Adam Calderon
- More info on InterKnowlogy www.InterKnowlogy.com
- Contact Information
- E-mail adamc_at_InterKnowlogy.com
- Phone 760-930-0075 x274
- Blog http//blogs.InterKnowlogy.com/AdamCalderon
- About Adam Calderon
- Microsoft MVP C
- Microsoft UI Server Frameworks Advisory Council
- Developer / Author / Speaker / Teacher
3What We Will Cover
- Binding data to UI Elements
- Binding to Business Classes
- Working with DataSources
- Binding to Collections
- Using Converters to convert data during Binding
- Using Data Templates to visualize data
- Using Validators to validate user input
4Agenda
- Connecting UI Elements
- Binding to Business Classes
- DataSources
- Binding to Collections
- Converting Data
- Data Templates
- Data Validation
5Data Binding OverviewData Binding Concepts
- Binding Components
- Target Object
- Target Property
- Binding Source
- Path
- Target Property Must be a dependency property
6Data Binding OverviewBinding Modes
- OneWay
- TwoWay
- OneWayToSource
- OneTime
7Data Binding OverviewWhat Triggers Updates
- Triggering supported by TwoWay or OneWayToSource
mode of binding - Dependency property or INotifyPropertyChanged
- UpdateSourceTrigger property
- LostFocus/PropertyChanged/Explicit
8Data Binding OverviewData Binding Methods (1)
- Binding using XAML
- Will be the method of choice for tools like
Visual Studio - Easy to follow
ltTextBox Name"targetTextBox" Grid.Column"1"
Grid.Row"1" Text"Binding
PathRent, ModeOneWayToSource,
UpdateSourceTriggerLostFocus"/gt ltTextBox
Grid.Column"1" Grid.Row"1"gt ltTextBox.Textgt
ltBinding Path"StartDate" Mode"TwoWay
UpdateSourceTrigger"LostFocus"
Converter"StaticResource dataConverter"/gt
lt/TextBox.Textgt lt/TextBoxgt
9Data Binding OverviewData Binding Methods (2)
- Binding using Code
- Good choice for dynamic situations
- Can be hard to follow in some cases
MyData myDataObject new MyData(DateTime.Now)
Binding myBinding new
Binding("MyDataProperty") myBinding.Source
myDataObject myText.SetBinding(TextBlock.TextPr
operty, myBinding)
10Demonstration 1
11Agenda
- Connecting UI Elements
- Binding to Business Classes
- DataSources
- Binding to Collections
- Converting Data
- Data Templates
- Data Validation
12Binding to Business ClassesOverview
- Classes must have a default constructor
- Properties must be public
- Cant bind to public members
- TwoWay binding requires implementing
INotifiyPropertyChange interface
13Binding to Business ClassesINotifyPropertyChange
- Contained in System.ComponentModel
- Must implement PropertyChangedEventHandler
- Must raise PropertyChange event when properties
get updated - UpdateSourceTrigger dictates when property is
updated from UI Element
14Binding to Business ClassesINotifyPropertyChange
Sample
class DateTimeSample INotifyPropertyChanged
public DateTimeSample()
private DateTime startDate public
DateTime StartDate get
return startDate set startDate
value OnPropertyChanged("StartDate")
public event PropertyChangedEventHandle
r PropertyChanged private void
OnPropertyChanged(String info)
if (PropertyChanged ! null)
PropertyChanged(this, new
PropertyChangedEventArgs(info))
15Binding to Business ClassesBest Practices
- Add INotifiyPropertyChange interface to classes
- Leave business logic inside of business class
- Use Converters (see later) to work with impedance
issues - Use Validators (see later) to handle logic that
is not appropriate in business classes
16Demonstration 2
17Agenda
- Connecting UI Elements
- Binding to Business Classes
- DataSources
- Binding to Collections
- Converting Data
- Data Templates
- Data Validation
18Data SourcesOverview
- Provide data to UI Elements
- Work in conjunction with DataContext
- Come in many flavors
- Business Objects
- ObjectDataProvider
- XmlDataProvider
- ADO.NET
19Data SourcesDataContext
- Element Assignment
- Inherited by child elements
- Child element usage
ltGrid.DataContextgt ltBinding
Source"StaticResource orderData"/gt lt/Grid.DataC
ontextgt
ltTextBox Text"Binding PathFirstName /gt
20Data SourcesObjectDataProvider
- Instantiates object in XAML
- Can be used for DataContext
- ConstructorParameters property
- MethodName property
- MethodParameters property
ltObjectDataProvider xKey"myDataSource"
ObjectType"xType srcPerson"gt
ltObjectDataProvider.ConstructorParametersgt
ltsystemStringgtJoelt/systemStringgt
lt/ObjectDataProvider.ConstructorParametersgt lt/Obje
ctDataProvidergt
21Data SourcesXmlDataProvider
- Instantiates object in XAML
- Can be used for DataContext
- Can use inline Xml inside the element itself
- Source property can be used to point to a Uri
- Document property can be set to an XmlDocument
22Data SourcesThings to Think About
- Xml and ADO.NET data sources most of the time
require additional overhead for validation logic - Use Validators (see later) and put validation
logic in them for Xml and ADO.NET data sources to
limit calling back to server
23Demonstration 3
24Agenda
- Connecting UI Elements
- Binding to Business Classes Data Sources
- DataSources
- Binding to Collections
- Converting Data
- Data Templates
- Data Validation
25Binding to CollectionsOverview
- Must implement IEnumerable
- Need to implement INotifyCollectionChange to
support TwoWay binding - Each object inside collection must support
INotifyPropertyChange
26Binding to CollectionsObservableCollectionltTgt
- Support IEnumerable
- Built-In Support for INotifyCollectionChange
- Standard Collection members
27Binding to CollectionsCollectionView
- Similar in concept to DataView
- Works over your data like DataView
- Filtering
- Sorting
- Grouping
- Current Record Pointer (CurrencyManager)
28Binding to CollectionsCollectionViewSource
- Serves as a source for data on an element
- Provides clean separation of views of the same
data - Supports Sorting by SortDescriptions collection
- Supports Grouping by GroupDescriptions collection
29Binding to CollectionsSortDescriptionsCollection
- Determines the sort order of a collection
- Can contain many sorts
- SortDescription structure properties
- PropertyName
- SortDirection
ltCollectionViewSource Source"StaticResource
places" xKey"cvs"gt ltCollectionViewSource.
SortDescriptionsgt ltscmSortDescription
PropertyName"CityName"/gt
lt/CollectionViewSource.SortDescriptionsgt lt/Collect
ionViewSourcegt MyCollectionViewSource.SortDescrip
tions.add(new SortDescription(CityName,ListSortD
irection.Ascending)
30Binding to CollectionsGroupDescriptionCollection
- Determines the grouping of a collection
- Creates groups based on PropertyName
- Can contain many entries
- PropertyGroupDescription properties
- PropertyName, Converter, StringComparison
ltCollectionViewSource Source"StaticResource
places" xKey"cvs"gt ltCollectionViewSource.Gro
upDescriptionsgt ltdatPropertyGroupDescript
ion PropertyName"State"/gt lt/CollectionViewSour
ce.GroupDescriptionsgt lt/CollectionViewSourcegt MyC
ollectionViewSource.GroupDescriptions.add(new
PropertyGroupDescription(State)
31Demonstration 4
32Agenda
- Connecting UI Elements
- Binding to Business Classes
- DataSources
- Binding to Collections
- Converting Data
- Data Templates
- Data Validation
33Converting DataOverview
- Used when data doesnt match between bindings
create a conversion class - When to use
- Culture changes needed
- Different View of data then native storage
- Incompatible data types between target and source
34Converting DataOut-of-Box Converters
- Contained in the System.Windows.Controls
namespace - BooleanToVisibilityConverter
- Converts True/False to Visible, Hidden or
Collapsed - BorderGapMaskConverter
- Represents a converter that converts the
dimensions of a GroupBox control into a
VisualBrush - MenuScrollingVisibilityConverter
- Data binding converter to handle the visibility
of repeat buttons in scrolling menus
35Converting DataHow this works
- IValueConverter
- Convert
- ConvertBack
- IMultiValueConverter
- Convert
- ConvertBack
36Converting Data IValueConverter Sample
//ValueConversion(source type, target
type) ValueConversion(typeof(DateTime),
typeof(String)) public class DateConverter
IValueConverter public object
Convert(object value, Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
string returnValue
string.Empty ... return
returnValue public object
ConvertBack(object value, Type targetType,
object parameter,
System.Globalization.CultureInfo culture)
DateTime resultDateTime ...
return resultDateTime
37Converting Data IMultiValueConverter Sample
public class NameConverter IMultiValueConverter
public object Convert(object values, Type
targetType, object parameter, CultureInfo
culture) string name
switch ((string)parameter)
case "FormatLastFirst"
name values1 ", " values0
break ...
return name
public object ConvertBack(object value, Type
targetTypes, object parameter, CultureInfo
culture) string
splitValues ((string)value).Split(' ')
return splitValues
38Demonstration 5
39Agenda
- Connecting UI Elements
- Binding to Business Classes
- DataSources
- Binding to Collections
- Converting Data
- Data Templates
- Data Validation
40Data TemplatesOverview
- Makes it easy to put content with data
- Easy to define visual styles for data
- Reusable and modifiable
41Data TemplatesTemplate Scenarios
- Single Binding
- Repeated Binding (ItemTemplate)
- Typed Based
- Heterogeneous Collections
- Template Selection
42Demonstration 6
43Agenda
- Connecting UI Elements
- Binding to Business Classes
- DataSources
- Binding to Collections
- Converting Data
- Data Templates
- Data Validation
44Data ValidationOverview
- Need for validation logic
- Integrated Solution
- Based on a ValidationRule and can have many
associated with element - Use ErrorTemplate property and a ControlTemplate
for visual representation
45Data ValidationProcess
- Called before any converter is called
- Applies to 2-Way and OneWayToSource binding modes
only - UpdateSourceTrigger dependent
- LostFocus
- PropertyChanged
- Explicit
46Data ValidationValidationRule
- Abstract Class
- Override Validate method
- Returns a ValidationResult class
public abstract class ValidationRule //
Methods protected ValidationRule()
public abstract ValidationResult Validate(object
value, CultureInfo cultureInfo) public
class ValidationResult static
ValidationResult() public ValidationResult(bo
ol isValid, object errorContent) public
object ErrorContent get public bool
IsValid get public static
ValidationResult ValidResult get
47Data ValidationBest Practices
- Create separate DLL for rules
- Use as a wrapper to common business logic
- Apply same logic on front end as backend
- Eases code maintenance
- If logic is in property setters
- Use the WPF validation rule ExceptionValidationRul
e - Raise exception in property setter
48Demonstration 7
49Session Summary (1)
- Data Binding is powerful
- INotifyPropertyChange enables business objects to
participate in TwoWay binding - ObjectDataSource and XmlDataSource provide XAML
based source instantiation - CollectionView and CollectionViewSource make
working with collections easy
50Session Summary (2)
- Converters provides conversion functionality
during the binding processes - Data Templates provide a rich way to visualize
data - Data Validation provides flexible way to validate
user input during the binding process
51For More Information
- MSDN Links
- Microsoft Windows Vista development center
http//msdn2.microsoft.com/en-us/windowsvista/defa
ult.aspx - Microsoft .NET Framework 3.0 for developers
http//msdn.microsoft.com/winfx/ - Other Links
- Microsoft .NET Framework http//www.netfx3.com/
52Additional Resources
53Adam Calderon
- More info on InterKnowlogy www.InterKnowlogy.com
- Contact Information
- E-mail adamc_at_InterKnowlogy.com
- Phone 760-930-0075 x274
- Blog http//blogs.InterKnowlogy.com/AdamCalderon
- About Adam Calderon
- Microsoft MVP C
- Microsoft UI Server Frameworks Advisory Council
- Developer / Author / Speaker / Teacher