Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 29

Visual Studio® 2008:

Windows® Presentation
Foundation
Module 4: Data Binding
• Overview of Data Binding

• Creating a Data Binding

• Implementing Property Change Notification

• Converting Data

• Validating Data
Lesson: Overview of Data Binding
• The WPF Data-Binding Model

• Binding Sources and Binding Targets

• Data-Binding Modes
The WPF Data-Binding Model

Managed Object

ADO.NET Data Source

XML Data

UI Element
Binding Sources and Binding Targets

Data-binding components:

• Binding target object


• Binding target dependency property
• Binding source
• Path to the binding source property

Binding Target Object Binding Source Object

Dependency
Property
Property
Data-Binding Modes

WPF supports four data-binding modes:

• OneWay • OneWayToSource
• TwoWay • OneTime

Binding Object

OneWay
TwoWay
OneWayToSource
OneTime

Binding Target Binding Source


Lesson: Creating a Data Binding
• Binding to a Class Property

• Binding Multiple Controls to a Class

• Binding to a Full Object

• Binding to XML Data

• Binding to Another User Interface Element

• Demonstration: Binding to Different Data Sources


Binding to a Class Property

To bind a control property to a class property:

• Define a resource that specifies the binding source class


• Specify the class property for binding in the Path

<DockPanel xmlns:c="clr-namespace:MyNamespace">

<DockPanel.Resources>
<c:MyClass x:Key="mySource" /> Path
</DockPanel.Resources>

<Button Background=
"{Binding Path=ColorName,
Source={StaticResource mySource}}">
...
</Button>
Source
</DockPanel>
Binding Multiple Controls to a Class

To bind multiple controls to class properties:

• Set the DataContext for a parent element


• Bind controls to the class properties

<DockPanel xmlns:c="clr-namespace:MyNamespace">
<DockPanel.Resources>...</DockPanel.Resources>
<DockPanel.DataContext>
<Binding Source="{StaticResource mySource}"/> Source
</DockPanel.DataContext>
<Button Background="{Binding Path=BackColorName}">
...
</Button>
<TextBox Foreground="{Binding Path=ForeColorName}">
...
</TextBox> Path
</DockPanel>
Binding to a Full Object

To bind to a full object:

• Omit the Path property in the Binding object


• Use the empty binding syntax if the Source is inherited

<DockPanel
xmlns:sys="clr-namespace:System;assembly=mscorlib">
<DockPanel.Resources>
<sys:String x:Key="myData">Hello World!</sys:String>
</DockPanel.Resources>
<DockPanel.DataContext> Source
<Binding Source="{StaticResource myData}"/>
</DockPanel.DataContext>
<Label Content="{Binding}">
</DockPanel> Empty binding
syntax
Binding to XML Data

To bind to a XML data:

• Use the XPath property in the Binding object


• Use the Path property to bind to the node properties

<ListBox> Source
<ListBox.ItemsSource>
<Binding Source="{StaticResource inventoryData}"
XPath="*[@Stock='out'] | *[@Number>=8 or
@Number=3]"/>
</ListBox.ItemsSource> XPath query
...
<TextBlock Text="{Binding XPath=Title}">
<TextBlock.Tooltip>
<TextBlock
Text="{Binding Path=Attributes[0].Value}" />
</TextxBlock.Tooltip>
</TextBlock>
... Node binding
</ListBox>
Binding to Another User Interface Element

To bind to a UI element:

Use the ElementName property in the Binding object

Source
element

<StackPanel>
<ComboBox x:Name="myComboBox" SelectedIndex="0">
...
</ComboBox>
<Canvas Background="{Binding
ElementName=myComboBox, Path=SelectedItem.Content}"
Height="100"
Width="100" />
Path
</StackPanel>

ElementName
Demonstration: Binding to Different Data Sources
In this demonstration, you will see how to:
• Bind to a class property

• Bind multiple controls to a class

• Bind to a full object

• Bind to XML data

• Bind to another UI element


Lesson: Implementing Property Change
Notification
• What Are Property Change Notifications?

• Propagating Property Change Notifications to a Binding


Target
• Propagating Value Changes to a Binding Source

• Demonstration: Triggering Source Updates


What Are Property Change Notifications?

Bindings listen for changes in the target property


and propagate them back to the source

The time when the update happens is defined by the


UpdateSourceTrigger property

Binding Object

OneWay
Binding TwoWay Binding
Target Source

OneWayToSource

UpdateSourceTrigger
Propagating Property Change Notifications to a
Binding Target

Use dependency properties for visual elements

To implement the INotifyPropertyChanged interface:


• Declare the PropertyChanged event
• Create the OnPropertyChanged method
• Call the OnPropertyChanged method

public class Person : INotifyPropertyChanged


{
public event PropertyChangedEventHandler
PropertyChanged;

// Raise the PropertyChanged event


// when property values in the class change.
}
Propagating Value Changes to a Binding Source

Specify the timing of binding source updates by


using the UpdateSourceTrigger property

• Default
• Explicit
• LostFocus
• PropertyChanged

<TextBox Width="100">
<TextBox.Text>
<Binding Source="{StaticResource myData}"
Path="ColorName"
UpdateSourceTrigger="PropertyChanged" />
</TextBox.Text>
</TextBox>
Demonstration: Triggering Source Updates
In this demonstration, you will see how to:
• Propagate changes to the binding target

• Propagate value changes to a binding source


Lesson 4: Converting Data
• Default Data Conversions

• Implementing a Custom Value Converter


Default Data Conversions

The data type of the binding source property must be


compatible with the binding target property

• WPF performs default data type conversion, if possible


• An error occurs if no default conversion is possible

Binding Target Binding Source

Button Object Default MyData Object


Background Conversion ColorName
Property Property
(of type Brush) (of type String)
Implementing a Custom Value Converter

To implement a custom value converter class:


• Define a class that implements IValueConverter
• Annotate the class with the ValueConversion attribute
• Implement the Convert and ConvertBack methods

Background ColorName
Property ColorBrush- Property
Converter
(of type Brush) (of type String)
Lesson: Validating Data
• Default Data Validation

• Providing Visual Validation Feedback

• Defining a Custom Validation Rule

• Specifying Validation Rules by Using XAML


Default Data Validation

WPF applications can validate user input

• Associate validation rules with a Binding object


• Test the type, range, or format of user input

Binding Target Binding Source

Dependency
Validation Converter Property
Property

<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
Providing Visual Validation Feedback

You can provide visual feedback by using a validation


template

• Define a ControlTemplate for the validation template


• Set control location by using AdornedElementPlaceholder
• Apply validation rule by setting Validation.ErrorTemplate

<ControlTemplate x:Key="errorTemplate">
<DockPanel>
<TextBlock Foreground="Red">!</TextBlock>
<AdornedElementPlaceholder/>
</DockPanel>
</ControlTemplate>

<TextBox Validation.ErrorTemplate =
"{StaticResource errorTemplate}" ...>
Defining a Custom Validation Rule

To implement a custom validation rule:

• Define a class that derives from ValidationRule


• Implement the Validate method

public class FutureDateRule : ValidationRule


{
public override ValidationResult Validate(
object value, CultureInfo ci)
{
...
}
}
Specifying Validation Rules by Using XAML

To use a custom validation rule in XAML:

• Set the ValidationRules property for a Binding


• Specify the name of the custom validation class

<TextBox xmlns:src="clr-namespace:MySample">
<TextBox.Text>
<Binding ...> ValidationRules
<Binding.ValidationRules>
<src:FutureDateRule />
</Binding.ValidationRules>
</Binding> Custom validation
</TextBox.Text> class
</TextBox>
Lab: Implementing a Data-Bound Application
• Exercise 1: Creating Data Bindings

• Exercise 2: Implementing Property Change Notification

• Exercise 3: Converting Data

• Exercise 4: Validating Data

Logon information
Virtual machine 6460A-LON-DEV-04

User name Student

Password Pa$$w0rd

Estimated time: 60 minutes


Lab Review
• How do you create a data binding?

• Which interface do you use to implement property change


notification?
• Which interface do you use to implement a custom value
converter?
• How do you define validation rules for a Binding?
Module Review and Takeaways
• Review Questions

• Best Practices

You might also like