Module 7 Data Binding to Collections. Module Overview Binding to Collections of Objects Using...

Preview:

Citation preview

Module 7

Data Binding to Collections

Module Overview

• Binding to Collections of Objects

• Using Collection Views

• Create Master-Detail User Interfaces

• Using Data Templates

Lesson 1: Binding to Collections of Objects

• Overview of Binding to Collections

• Understanding Observable Collections

• Defining an Observable Collection Class

• Introduction to LINQ

• Binding to Data Objects

Overview of Binding to Collections

You can bind item controls to a collection of objectsYou can bind item controls to a collection of objects

For example: bind a ListBox control to a database result setFor example: bind a ListBox control to a database result set

ItemsSource property

ItemsSource property ValueValue

Binding target Binding source

ItemsControl object Collection object

OneWay

Binding object

Understanding Observable Collections

VenusEarthMarsCeresJupiterSaturnUranusNeptunePlutoEris

Implements INotifyCollectionChanged

ItemsSourceproperty

Observable collection

New data items

CollectionChanged

VenusEarthMarsJupiterSaturnUranusNeptune

Mercury

Defining an Observable Collection Class

To define and use an observable collection class:To define and use an observable collection class:

public class NameList : ObservableCollection<Person> { ... public class PersonName { ... }}

public class NameList : ObservableCollection<Person> { ... public class PersonName { ... }}

<Window ... xmlns:c="clr-namespace:MySample"> <Window.Resources> <c:NameList x:Key="list"/> </Window.Resources> <ListBox ItemsSource = "{Binding Source={StaticResource list}}"/></Window>

<Window ... xmlns:c="clr-namespace:MySample"> <Window.Resources> <c:NameList x:Key="list"/> </Window.Resources> <ListBox ItemsSource = "{Binding Source={StaticResource list}}"/></Window>

• Define a class that extends ObservableCollection(T)

• Create an XAML resource to represent the class and bind to it

• Define a class that extends ObservableCollection(T)

• Create an XAML resource to represent the class and bind to it

Introduction to LINQ

Language-Integrated QueryLanguage-Integrated Query

Visual C#Visual C# Visual BasicVisual Basic OthersOthers

Standard

query

operators

Standard

query

operators

DLinq

(ADO.NET)

DLinq

(ADO.NET)

XLinq

(System.Xml)

XLinq

(System.Xml)

CLR objects Relational data XML

Binding to Data Objects

WPF enables you to bind to ADO.NET classes such as:WPF enables you to bind to ADO.NET classes such as:

• DataSet

• DataTable

• DataView

• DataSet

• DataTable

• DataView

To bind to an ADO.NET object:To bind to an ADO.NET object:

• Populate an ADO.NET object such as DataSet

• Set the DataContext property of a control such as ListBox

• Create bindings to the required data objects by using properties such as ItemsSource

• Populate an ADO.NET object such as DataSet

• Set the DataContext property of a control such as ListBox

• Create bindings to the required data objects by using properties such as ItemsSource

Lesson 2: Using Collection Views

• Understanding Collection Views

• Creating and Using a Collection View

• Sorting Data by Using a Collection View

• Filtering Data by Using a Collection View

• Grouping Data by Using a Collection View

Understanding Collection Views

Source collection

MercuryVenusEarthMarsCeresJupiterSaturnUranusNeptunePlutoEris

CeresEarthErisJupiterMarsMercuryNeptunePlutoSaturnUranusVenus

Sort

MercuryVenusEarthMarsJupiterSaturnUranusNeptune

Filter

MercuryVenusEarthMarsJupiterSaturnUranusNeptune

CeresPlutoEris

Group

Creating and Using a Collection View

<ListBox ItemsSource="{Binding Source={StaticResource listView}}"> ...</ListBox>

<ListBox ItemsSource="{Binding Source={StaticResource listView}}"> ...</ListBox>

To create and use a collection by using XAML:To create and use a collection by using XAML:

<Window.Resources> <CollectionViewSource Source="{Binding Source={x:Static Application.Current}, Path=AuctionItems}" x:Key="listView" /> ...</Window.Resources>

<Window.Resources> <CollectionViewSource Source="{Binding Source={x:Static Application.Current}, Path=AuctionItems}" x:Key="listView" /> ...</Window.Resources>

• Define a CollectionViewSource resource

• Bind a UI control to the resource

• Define a CollectionViewSource resource

• Bind a UI control to the resource

Sorting Data by Using a Collection View

To sort data by using a collection view:To sort data by using a collection view:

view.SortDescriptions.Add( new SortDescription("CategoryName", ListSortDirection.Ascending));

view.SortDescriptions.Add( new SortDescription("ProductName", ListSortDirection.Ascending));

view.SortDescriptions.Add( new SortDescription("CategoryName", ListSortDirection.Ascending));

view.SortDescriptions.Add( new SortDescription("ProductName", ListSortDirection.Ascending));

• Create a SortDescription object

• Add it to the SortDescriptions collection

• Create a SortDescription object

• Add it to the SortDescriptions collection

Filtering Data by Using a Collection View

listView.Filter += new FilterEventHandler(ShowBargains); ...private void ShowBargains(object s, FilterEventArgs e) { Product p = e.Item as Product; if (p != null) { if (p.CurrentPrice >= 25) e.Accepted = false; else e.Accepted = true; } }

listView.Filter += new FilterEventHandler(ShowBargains); ...private void ShowBargains(object s, FilterEventArgs e) { Product p = e.Item as Product; if (p != null) { if (p.CurrentPrice >= 25) e.Accepted = false; else e.Accepted = true; } }

To filter data by using a collection view:To filter data by using a collection view:

• Implement a handler for the Filter event

• In the event-handler method, accept or reject items

• Implement a handler for the Filter event

• In the event-handler method, accept or reject items

Grouping Data by Using a Collection View

PropertyGroupDescription desc = new PropertyGroupDescription();desc.PropertyName = "CategoryName";

listView.GroupDescriptions.Add(desc);

PropertyGroupDescription desc = new PropertyGroupDescription();desc.PropertyName = "CategoryName";

listView.GroupDescriptions.Add(desc);

To group data by using a collection view:To group data by using a collection view:

• Create a PropertyGroupDescription object

• Add it to the GroupDescriptions collection

• Create a PropertyGroupDescription object

• Add it to the GroupDescriptions collection

Lesson 3: Creating Master-Detail User Interfaces

• Understanding Master-Detail User Interfaces

• Creating a Master-Detail User Interface

• Demonstration: Creating a Master-Detail UI by Using a DataGrid Control

Understanding Master-Detail User Interfaces

Master-detail UIs:Master-detail UIs:

• Represent a one-to-many relationship

• Are a form of filtering

• Enable you to navigate through many items

• Represent a one-to-many relationship

• Are a form of filtering

• Enable you to navigate through many items

Creating a Master-Detail User Interface

<ListBox ItemsSource="{Binding Source={StaticResource listView}}"> ...<ContentControl Content="{Binding Source={StaticResource view}}"> ...

<ListBox ItemsSource="{Binding Source={StaticResource listView}}"> ...<ContentControl Content="{Binding Source={StaticResource view}}"> ...

To bind master-detail controls to a collection view:To bind master-detail controls to a collection view:

• Define a CollectionViewSource resource

• Bind multiple controls to the resource

• Define a CollectionViewSource resource

• Bind multiple controls to the resource

You must set the IsSynchronizedWithCurrentItem property to True if the data source is not a collectionYou must set the IsSynchronizedWithCurrentItem property to True if the data source is not a collection

Demonstration: Creating a Master Detail UI by Using a DataGrid control

In this demonstration, you will see how to:

• Use a DataGrid control to create a master view

• Use sample data with a DataGrid control

• Create a details view that is linked to the master view

Lesson 4: Using Data Templates

• Understanding Data Templates

• Defining and Using a Data Template

• Defining a Data Template As a Resource

• Using Data Triggers in a Data Template

• Understanding Data Template Selectors

Understanding Data Templates

Andy Jacobs43Robert Brown34Kelly Krout63Lola Jacobsen23

MySample.PersonMySample.PersonMySample.PersonMySample.Person

Data Template

Defining and Using a Data Template

<ListBox ItemsSource="{Binding Source={StaticResource list}}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=FirstName}" /> <TextBlock Text="{Binding Path=LastName}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>

<ListBox ItemsSource="{Binding Source={StaticResource list}}"> <ListBox.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Path=FirstName}" /> <TextBlock Text="{Binding Path=LastName}"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate></ListBox>

To define and use a data template:To define and use a data template:

• Define a DataTemplate element

• Add it to the ItemTemplate or ContentTemplate property

• Define a DataTemplate element

• Add it to the ItemTemplate or ContentTemplate property

Defining a Data Template As a Resource

<Window.Resources> <DataTemplate x:Key="myDataTemplate"> <StackPanel> <TextBlock Text="{Binding Path=FirstName}" /> <TextBlock Text="{Binding Path=LastName}"/> </StackPanel> </DataTemplate> </Window.Resources>

<ListBox ItemsSource="{Binding Source={StaticResource list}}" ItemTemplate="{StaticResource myDataTemplate}" />

<Window.Resources> <DataTemplate x:Key="myDataTemplate"> <StackPanel> <TextBlock Text="{Binding Path=FirstName}" /> <TextBlock Text="{Binding Path=LastName}"/> </StackPanel> </DataTemplate> </Window.Resources>

<ListBox ItemsSource="{Binding Source={StaticResource list}}" ItemTemplate="{StaticResource myDataTemplate}" />

You define reusable data templates as resources by setting the x:Key or DataType property on the DataTemplateYou define reusable data templates as resources by setting the x:Key or DataType property on the DataTemplate

Using Data Triggers in a Data Template

<DataTemplate x:Key="myDataTemplate"> <DataTemplate.Triggers> <DataTrigger Binding="{Binding Path=Gender}" Value="Male"> <Setter TargetName="border" Property="Foreground" Value="Blue"/> </DataTrigger> </DataTemplate.Triggers> </DataTemplate>

<DataTemplate x:Key="myDataTemplate"> <DataTemplate.Triggers> <DataTrigger Binding="{Binding Path=Gender}" Value="Male"> <Setter TargetName="border" Property="Foreground" Value="Blue"/> </DataTrigger> </DataTemplate.Triggers> </DataTemplate>

To define a data trigger:To define a data trigger:

• Define a DataTrigger element

• Set the Binding and Value properties on the DataTrigger

• Add Setter child elements to set control properties

• Define a DataTrigger element

• Set the Binding and Value properties on the DataTrigger

• Add Setter child elements to set control properties

Understanding Data Template Selectors

<ListBox ItemTemplateSelector="{StaticResource myTemplateSelector}"> ...</ListBox>

<ListBox ItemTemplateSelector="{StaticResource myTemplateSelector}"> ...</ListBox>

To create and use a data template selector:To create and use a data template selector:

public class MyDataTemplateSelector : DataTemplateSelector{ public override DataTemplate SelectTemplate( object item, DependencyObject container) { ... }}

public class MyDataTemplateSelector : DataTemplateSelector{ public override DataTemplate SelectTemplate( object item, DependencyObject container) { ... }}

• Define a new class that inherits from the class DataTemplateSelector

• Override the SelectTemplate method

• Define a new class that inherits from the class DataTemplateSelector

• Override the SelectTemplate method

Lab: Data Binding to Collections

• Exercise 1: Binding to Collections of Data

• Exercise 2: Using Collection Views

• Exercise 3: Creating Master-Detail User Interfaces

• Exercise 4: Using Data Templates

Logon information

Estimated time: 60 minutes

Lab Scenario

You have been asked to update the Work Orders application to include a master-detail view of the work orders so that users can create, view, update, and delete work orders as required.

Lab Review

Review Questions

• What is the purpose of the CollectionViewSource element?

• What is the purpose of inheriting from the DataTemplateSelector class?

Module Review and Takeaways

• Review Questions

• Best Practices

• Tools

Recommended