6460a_04

29
Visual Studio ® 2008: Windows ® Presentation Foundation

Upload: api-3700231

Post on 11-Apr-2015

101 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: 6460A_04

Visual Studio® 2008: Windows® Presentation

Foundation

Page 2: 6460A_04

Module 4: Data Binding

• Overview of Data Binding

• Creating a Data Binding

• Implementing Property Change Notification

• Converting Data

• Validating Data

Page 3: 6460A_04

Lesson: Overview of Data Binding

• The WPF Data-Binding Model

• Binding Sources and Binding Targets

• Data-Binding Modes

Page 4: 6460A_04

The WPF Data-Binding Model

Managed Object

ADO.NET Data Source

XML Data

UI Element

Page 5: 6460A_04

Binding Sources and Binding Targets

Data-binding components:Data-binding components:

• Binding target object

• Binding target dependency property

• Binding source

• Path to the binding source property

• Binding target object

• Binding target dependency property

• Binding source

• Path to the binding source property

Dependency Property

Dependency Property Property Property

Binding Target Object Binding Source Object

Page 6: 6460A_04

Data-Binding Modes

Binding Target Binding Source

Binding Object

OneWay

TwoWay

OneWayToSource

OneTime

OneWay

TwoWay

OneWayToSource

OneTime

WPF supports four data-binding modes:WPF supports four data-binding modes:

• OneWay• TwoWay

• OneWay• TwoWay

• OneWayToSource• OneTime

Page 7: 6460A_04

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

Page 8: 6460A_04

Binding to a Class Property

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

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

<Button Background= "{Binding Path=ColorName, Source={StaticResource mySource}}"> ... </Button>

</DockPanel>

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

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

<Button Background= "{Binding Path=ColorName, Source={StaticResource mySource}}"> ... </Button>

</DockPanel>

To bind a control property 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

• Define a resource that specifies the binding source class

• Specify the class property for binding in the Path

Path

Source

Page 9: 6460A_04

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

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

Binding Multiple Controls to a Class

To bind multiple controls to class properties:To bind multiple controls to class properties:

• Set the DataContext for a parent element

• Bind controls to the class properties

• Set the DataContext for a parent element

• Bind controls to the class properties

Source

PathPath

Page 10: 6460A_04

Binding to a Full Object

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

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

To bind 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

• Omit the Path property in the Binding object

• Use the empty binding syntax if the Source is inherited

Source

Empty binding syntax

Page 11: 6460A_04

Binding to XML Data

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

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

To bind to a 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

• Use the XPath property in the Binding object

• Use the Path property to bind to the node properties

Source

Node binding

XPath queryXPath query

Page 12: 6460A_04

Binding to Another User Interface Element

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

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

To bind to a UI element:To bind to a UI element:

Use the ElementName property in the Binding object Use the ElementName property in the Binding object

Source element

ElementName

Path

Page 13: 6460A_04

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

Page 14: 6460A_04

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

Page 15: 6460A_04

What Are Property Change Notifications?

BindingTarget

BindingSource

Binding Object

OneWay

TwoWay

OneWayToSource

OneWay

TwoWay

OneWayToSource

Bindings listen for changes in the target property and propagate them back to the sourceBindings 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 propertyThe time when the update happens is defined by the UpdateSourceTrigger property

UpdateSourceTrigger

Page 16: 6460A_04

Propagating Property Change Notifications to a Binding Target

public class Person : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged;

// Raise the PropertyChanged event // when property values in the class change.}

public class Person : INotifyPropertyChanged{ public event PropertyChangedEventHandler PropertyChanged;

// Raise the PropertyChanged event // when property values in the class change.}

To implement the INotifyPropertyChanged interface:To implement the INotifyPropertyChanged interface:

1. Declare the PropertyChanged event

2. Create the OnPropertyChanged method

3. Call the OnPropertyChanged method

1. Declare the PropertyChanged event

2. Create the OnPropertyChanged method

3. Call the OnPropertyChanged method

Use dependency properties for visual elementsUse dependency properties for visual elements

Page 17: 6460A_04

Propagating Value Changes to a Binding Source

<TextBox Width="100"> <TextBox.Text> <Binding Source="{StaticResource myData}" Path="ColorName" UpdateSourceTrigger="PropertyChanged" /> </TextBox.Text></TextBox>

<TextBox Width="100"> <TextBox.Text> <Binding Source="{StaticResource myData}" Path="ColorName" UpdateSourceTrigger="PropertyChanged" /> </TextBox.Text></TextBox>

Specify the timing of binding source updates by using the UpdateSourceTrigger propertySpecify the timing of binding source updates by using the UpdateSourceTrigger property

• Default

• Explicit

• LostFocus

• PropertyChanged

• Default

• Explicit

• LostFocus

• PropertyChanged

Page 18: 6460A_04

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

Page 19: 6460A_04

Lesson 4: Converting Data

• Default Data Conversions

• Implementing a Custom Value Converter

Page 20: 6460A_04

Default Data Conversions

The data type of the binding source property must be compatible with the binding target propertyThe 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

• WPF performs default data type conversion, if possible

• An error occurs if no default conversion is possible

Background Property

(of type Brush)

Background Property

(of type Brush)

ColorName Property

(of type String)

ColorName Property

(of type String)

Binding Target Binding Source

Button Object MyData ObjectDefaultConversion

Page 21: 6460A_04

To implement a custom value converter class:To implement a custom value converter class:

Implementing a Custom Value Converter

• Define a class that implements IValueConverter

• Annotate the class with the ValueConversion attribute

• Implement the Convert and ConvertBack methods

• Define a class that implements IValueConverter

• Annotate the class with the ValueConversion attribute

• Implement the Convert and ConvertBack methods

Background Property

(of type Brush)

Background Property

(of type Brush)

ColorName Property

(of type String)

ColorName Property

(of type String)

ColorBrush-Converter

ColorBrush-Converter

Page 22: 6460A_04

Lesson: Validating Data

• Default Data Validation

• Providing Visual Validation Feedback

• Defining a Custom Validation Rule

• Specifying Validation Rules by Using XAML

Page 23: 6460A_04

WPF applications can validate user inputWPF applications can validate user input

Default Data Validation

Dependency Property

Dependency Property Property Property

Binding Target Binding Source

Validation Validation Converter Converter

• Associate validation rules with a Binding object

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

• Associate validation rules with a Binding object

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

<Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules>

<Binding.ValidationRules> <ExceptionValidationRule /> </Binding.ValidationRules>

Page 24: 6460A_04

Providing Visual Validation Feedback

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

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

<TextBox Validation.ErrorTemplate = "{StaticResource errorTemplate}" ...><TextBox Validation.ErrorTemplate = "{StaticResource errorTemplate}" ...>

You can provide visual feedback by using a validation templateYou 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

• Define a ControlTemplate for the validation template

• Set control location by using AdornedElementPlaceholder

• Apply validation rule by setting Validation.ErrorTemplate

Page 25: 6460A_04

Defining a Custom Validation Rule

public class FutureDateRule : ValidationRule { public override ValidationResult Validate( object value, CultureInfo ci) { ... } }

public class FutureDateRule : ValidationRule { public override ValidationResult Validate( object value, CultureInfo ci) { ... } }

To implement a custom validation rule:To implement a custom validation rule:

1. Define a class that derives from ValidationRule

2. Implement the Validate method

1. Define a class that derives from ValidationRule

2. Implement the Validate method

Page 26: 6460A_04

<TextBox xmlns:src="clr-namespace:MySample"> <TextBox.Text> <Binding ...> <Binding.ValidationRules> <src:FutureDateRule /> </Binding.ValidationRules> </Binding> </TextBox.Text></TextBox>

<TextBox xmlns:src="clr-namespace:MySample"> <TextBox.Text> <Binding ...> <Binding.ValidationRules> <src:FutureDateRule /> </Binding.ValidationRules> </Binding> </TextBox.Text></TextBox>

Specifying Validation Rules by Using XAML

To use a custom validation rule in XAML:To use a custom validation rule in XAML:

• Set the ValidationRules property for a Binding

• Specify the name of the custom validation class

• Set the ValidationRules property for a Binding

• Specify the name of the custom validation class

ValidationRules

Custom validation class

Page 27: 6460A_04

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

Page 28: 6460A_04

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?

Page 29: 6460A_04

Module Review and Takeaways

• Review Questions

• Best Practices