An%20Introduction%20to%20Data%20Binding%20in%20Windows%20Presentation%20Foundation%20(WPF) - PowerPoint PPT Presentation

About This Presentation
Title:

An%20Introduction%20to%20Data%20Binding%20in%20Windows%20Presentation%20Foundation%20(WPF)

Description:

UpdateSourceTrigger dictates when property is updated from UI Element ... Use ErrorTemplate property and a ControlTemplate for visual representation ... – PowerPoint PPT presentation

Number of Views:985
Avg rating:3.0/5.0
Slides: 54
Provided by: staci2
Category:

less

Transcript and Presenter's Notes

Title: An%20Introduction%20to%20Data%20Binding%20in%20Windows%20Presentation%20Foundation%20(WPF)


1
An Introduction to Data Binding in Windows
Presentation Foundation (WPF)
  • Adam Calderon C MVP
  • Application Development Practice Lead
  • Interknowlogy

2
Adam 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

3
What 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

4
Agenda
  • Connecting UI Elements
  • Binding to Business Classes
  • DataSources
  • Binding to Collections
  • Converting Data
  • Data Templates
  • Data Validation

5
Data Binding OverviewData Binding Concepts
  • Binding Components
  • Target Object
  • Target Property
  • Binding Source
  • Path
  • Target Property Must be a dependency property

6
Data Binding OverviewBinding Modes
  • OneWay
  • TwoWay
  • OneWayToSource
  • OneTime

7
Data Binding OverviewWhat Triggers Updates
  • Triggering supported by TwoWay or OneWayToSource
    mode of binding
  • Dependency property or INotifyPropertyChanged
  • UpdateSourceTrigger property
  • LostFocus/PropertyChanged/Explicit

8
Data 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
9
Data 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)
10
Demonstration 1
  • Connecting UI Elements

11
Agenda
  • Connecting UI Elements
  • Binding to Business Classes
  • DataSources
  • Binding to Collections
  • Converting Data
  • Data Templates
  • Data Validation

12
Binding to Business ClassesOverview
  • Classes must have a default constructor
  • Properties must be public
  • Cant bind to public members
  • TwoWay binding requires implementing
    INotifiyPropertyChange interface

13
Binding 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

14
Binding 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))

15
Binding 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

16
Demonstration 2
  • Binding to Classes

17
Agenda
  • Connecting UI Elements
  • Binding to Business Classes
  • DataSources
  • Binding to Collections
  • Converting Data
  • Data Templates
  • Data Validation

18
Data SourcesOverview
  • Provide data to UI Elements
  • Work in conjunction with DataContext
  • Come in many flavors
  • Business Objects
  • ObjectDataProvider
  • XmlDataProvider
  • ADO.NET

19
Data 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
20
Data 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
21
Data 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

22
Data 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

23
Demonstration 3
  • Data Sources

24
Agenda
  • Connecting UI Elements
  • Binding to Business Classes Data Sources
  • DataSources
  • Binding to Collections
  • Converting Data
  • Data Templates
  • Data Validation

25
Binding to CollectionsOverview
  • Must implement IEnumerable
  • Need to implement INotifyCollectionChange to
    support TwoWay binding
  • Each object inside collection must support
    INotifyPropertyChange

26
Binding to CollectionsObservableCollectionltTgt
  • Support IEnumerable
  • Built-In Support for INotifyCollectionChange
  • Standard Collection members

27
Binding to CollectionsCollectionView
  • Similar in concept to DataView
  • Works over your data like DataView
  • Filtering
  • Sorting
  • Grouping
  • Current Record Pointer (CurrencyManager)

28
Binding 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

29
Binding 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)
30
Binding 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)
31
Demonstration 4
  • Binding to Collections

32
Agenda
  • Connecting UI Elements
  • Binding to Business Classes
  • DataSources
  • Binding to Collections
  • Converting Data
  • Data Templates
  • Data Validation

33
Converting 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

34
Converting 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

35
Converting DataHow this works
  • IValueConverter
  • Convert
  • ConvertBack
  • IMultiValueConverter
  • Convert
  • ConvertBack

36
Converting 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
37
Converting 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
38
Demonstration 5
  • Converting Data

39
Agenda
  • Connecting UI Elements
  • Binding to Business Classes
  • DataSources
  • Binding to Collections
  • Converting Data
  • Data Templates
  • Data Validation

40
Data TemplatesOverview
  • Makes it easy to put content with data
  • Easy to define visual styles for data
  • Reusable and modifiable

41
Data TemplatesTemplate Scenarios
  • Single Binding
  • Repeated Binding (ItemTemplate)
  • Typed Based
  • Heterogeneous Collections
  • Template Selection

42
Demonstration 6
  • Data Templates

43
Agenda
  • Connecting UI Elements
  • Binding to Business Classes
  • DataSources
  • Binding to Collections
  • Converting Data
  • Data Templates
  • Data Validation

44
Data 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

45
Data ValidationProcess
  • Called before any converter is called
  • Applies to 2-Way and OneWayToSource binding modes
    only
  • UpdateSourceTrigger dependent
  • LostFocus
  • PropertyChanged
  • Explicit

46
Data 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
47
Data 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

48
Demonstration 7
  • Data Validation

49
Session 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

50
Session 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

51
For 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/

52
Additional Resources
53
Adam 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
Write a Comment
User Comments (0)
About PowerShow.com