SlideShare a Scribd company logo
Windows Application Development with Microsoft .NET Framework 4
Configuring Data Binding
1. Binding to Data Sources (brief overview of the previous lecture)
2. Manipulating and Displaying Data
by Oleksiy Korotchyn
Binding an Item Control to a List
<ListBox
ItemsSource="{Binding Source={StaticResource myCollection}}"
DisplayMemberPath="FirstName"
/>
myCollection can be:
2
 Simple array
 Collection
 ADO.NET Object
 ObjectDataProvider
 XmlDataProvider
Binding a Single Property to a List
 To show Items Collection (ToString())
<Label Content="{Binding }"/>
 To show Current item:
<Label Content="{Binding /}"/>
3
Binding to Hierarchical Data
 For ADO.NET object:
<Label Content="{Binding
Path=ProductTypes/TypesCategoriesRelation/CategoryName.Length}" />
<!– Table /Relation /Row .Property -->
 For array of objects:
<Label Content="{Binding /PropertyObject.PropertyObject.MyProperty}"/>
<Label Content="{Binding Path=PropertyObject.PropertyObject.MyProperty}"/>
4
Navigating a Collection or List
To get a reference to ICollectionView:
System.ComponentModel.ICollectionView myView;
myView = CollectionViewSource.GetDefaultView(myCollection);
5
Binding to an Object with ObjectDataProvider
1) IsAsynchronous – indicates whether object creation and method calls are performed on the foreground thread
or on a background thread.
2) ObjectInstance – gets or sets the object used as the binding source.
 Let’s see example
6
Windows Application Development with Microsoft .NET Framework 4
Configuring Data Binding
1. Binding to Data Sources
2. Manipulating and Displaying Data
by Oleksiy Korotchyn
Data Templates
<DataTemplate>
<StackPanel>
<TextBlock>Company Name:</TextBlock>
<TextBlock Text="{Binding CompanyName}" />
<Label Content="{Binding Path=ContactName}"/>
</StackPanel>
</DataTemplate>
8
Data Templates
Setting the Data Template
<Label>
<Label.ContentTemplate>
<DataTemplate>
<!--Actual data template omitted-->
</DataTemplate>
</Label.ContentTemplate>
</Label>
9
Setting the Data Template
 Note that for item controls, the DisplayMemberPath and ItemTemplate properties are mutually exclusive.
(you can set one but not the other)
10
Using Converters to Apply Conditional Formatting in Data Templates
[ValueConversion(typeof(DateTime), typeof(Brush))]
public class DateBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo
culture)
{ … }
public object ConvertBack(object value, Type targetType, object parameter,
System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
11
Using DataTemplateSelector
 The DataTemplateSelector class enables you to assign data templates dynamically to collection objects based on
the content of the data.
12
Using DataTemplateSelector
public class DateDataTemplateSelector : DataTemplateSelector
{
public override DataTemplate SelectTemplate(object item, DependencyObject
container)
{
FrameworkElement element = container as FrameworkElement;
if (element != null && item != null && item is System.Data.DataRowView)
{return element.FindResource("BasicTemplate") as DataTemplate; }
return null; }}
13
Using DataTemplateSelector
<Window x:Class="MainWindow"
…
<Window.Resources>
<my:DateDataTemplateSelector x:Key="myTemplateSelector" />
</Window.Resources>
<ListBox ItemTemplateSelector="{StaticResource myTemplateSelector}" />
</Window>
14
Using DataTemplateSelector
 Let’s see example
15
Using Hierarchical Data Templates
Item-Related Properties of HierarchicalDataTemplate:
1) ItemBindingGroup – gets or sets the BindingGroup property that is copied to each child item.
2) ItemContainerStyle – gets or sets the Style property that is applied to the item container for each child item.
3) ItemContainerStyleSelector – gets or sets custom style-selection logic for a style that can be applied to each item
container.
4) ItemsSource – gets or sets the binding for this data template, which indicates where to find the collection that
represents the next level in the data hierarchy
16
Using Hierarchical Data Templates
Item-Related Properties of HierarchicalDataTemplate:
5) ItemStringFormat – gets or sets a composite string that specifies how to format the items in the next level in the
data hierarchy if they are displayed as strings.
6) ItemTemplate – gets or sets the data template to apply to the ItemTemplate property on a generated
HeaderedItemsControl control (such as MenuItem or TreeViewItem) to indicate how to display items from the
next level in the data hierarchy.
7) ItemTemplateSelector – gets or sets DataTemplateSelector to apply to the ItemTemplateSelector property on a
generated HeaderedItemsControl control (such as MenuItem or TreeViewItem) to indicate how to select a
template to display items from the next level in the data hierarchy
17
Using Hierarchical Data Templates
 Let’s see example
18
Sorting Data
 Bound data can be sorted through the default ICollectionView element for the data list
19
Sorting Data
System.ComponentModel.ICollectionView myView;
myView = CollectionViewSource.GetDefaultView(myCollection);
myView.SortDescriptions.Add(new
System.ComponentModel.SortDescription("LastName",
System.ComponentModel.ListSortDirection.Ascending));
20
Sorting Data
myView.SortDescriptions.Add(new
System.ComponentModel.SortDescription("LastName",
System.ComponentModel.ListSortDirection.Ascending));
myView.SortDescriptions.Add(new
System.ComponentModel.SortDescription("FirstName",
System.ComponentModel.ListSortDirection.Ascending));
21
Applying Custom Sorting
public class MyComparer : System.Collections.IComparer
{
public int Compare(object x, object y)
{
Employee empX = (Employee)x;
Employee empY = (Employee)y;
return empX.LastName.Length.CompareTo(empY.LastName.Length);
}
}
22
Applying Custom Sorting
System.ComponentModel.ICollectionView myView;
myView =(ListCollectionView)CollectionViewSource.GetDefaultView(myCollection);
myView.CustomSort = new MyComparer();
23
Grouping
System.ComponentModel.ICollectionView myView;
myView = CollectionViewSource.GetDefaultView(myCollection);
myView.GroupDescriptions.Add(new PropertyGroupDescription("EmployeeTitle"));
24
Grouping
Properties of GroupStyle:
 ContainerStyle – gets or sets the style applied to the GroupItem object generated for each item
 ContainerStyleSelector – represents an instance of StyleSelector that determines the appropriate style to use for
the container
 HeaderTemplate – gets or sets the template used to display the group header
 HeaderTemplateSelector – represents an instance of StyleSelector that determines the appropriate style to use
for the header
 Panel – gets or sets a template that creates the panel used to layout the items
25
Creating Custom Grouping
 To create a custom group, you must create a class that implements the IValueConverter interface, which exposes
two methods: Convert and ConvertBack.
26
Creating Custom Grouping
System.ComponentModel.ICollectionView myView;
myView = CollectionViewSource.GetDefaultView(myCollection);
myView.GroupDescriptions.Add(new PropertyGroupDescription("Region", new
RegionGrouper()));
27
Filtering Data
System.ComponentModel.ICollectionView myView;
myView = CollectionViewSource.GetDefaultView(myItems);
myView.Filter = new Predicate<object>(myFilter);
28
Filtering Data
public bool myFilter(object param)
{
return (param.ToString().Length > 8);
}
29
Filtering ADO.NET Objects
The filter expression is a string expression in the following format:
<ColumnName> <Operator> <Value>
BindingListCollectionView myView;
myView = (BindingListCollectionView)CollectionViewSource.GetDefaultView(myItems);
myView.CustomFilter = "Sandwich = 'Muffaletta'";
30
Filtering, Grouping and Sorting
 Let’s see example
31
32
Questions?

More Related Content

What's hot (20)

PPTX
Interface connection
myrajendra
 
PPT
2310 b 09
Krazy Koder
 
DOCX
Shopping Cart Code
hanaan wacan
 
PPTX
Advance Webpage Devlopment .NET
PandeyABHISHEK1
 
DOCX
Cart Page Code
hanaan wacan
 
PPT
Core Data Migration
Monica Kurup
 
PPT
Overview on NoSQL and MongoDB
harithakannan
 
PPTX
Disconnected Architecture and Crystal report in VB.NET
Everywhere
 
PPT
Dev308
guest2130e
 
PDF
Intake 38 data access 1
Mahmoud Ouf
 
PPTX
Lesson 05 Data Binding in WPF
Quang Nguyễn Bá
 
PPTX
Lesson 09 Resources and Settings in WPF
Quang Nguyễn Bá
 
PPTX
Lesson 06 Styles and Templates in WPF
Quang Nguyễn Bá
 
PDF
KMI System
Thirumavalavan Ganesan
 
PDF
Android contentprovider
Krazy Koder
 
PPT
ASP.NET Session 13 14
Sisir Ghosh
 
PDF
Flex3 data binding
guestdf3003
 
PDF
ASP.net Image Slideshow
Hock Leng PUAH
 
PPTX
Android content providers
Kurt Mbanje
 
Interface connection
myrajendra
 
2310 b 09
Krazy Koder
 
Shopping Cart Code
hanaan wacan
 
Advance Webpage Devlopment .NET
PandeyABHISHEK1
 
Cart Page Code
hanaan wacan
 
Core Data Migration
Monica Kurup
 
Overview on NoSQL and MongoDB
harithakannan
 
Disconnected Architecture and Crystal report in VB.NET
Everywhere
 
Dev308
guest2130e
 
Intake 38 data access 1
Mahmoud Ouf
 
Lesson 05 Data Binding in WPF
Quang Nguyễn Bá
 
Lesson 09 Resources and Settings in WPF
Quang Nguyễn Bá
 
Lesson 06 Styles and Templates in WPF
Quang Nguyễn Bá
 
Android contentprovider
Krazy Koder
 
ASP.NET Session 13 14
Sisir Ghosh
 
Flex3 data binding
guestdf3003
 
ASP.net Image Slideshow
Hock Leng PUAH
 
Android content providers
Kurt Mbanje
 

Similar to Configuring Data Binding part2 ABTO Software Lecture Korotchyn (20)

PPT
Complex Data Binding
Doncho Minkov
 
PPTX
WPF - Controls &amp; Data
Sharada Gururaj
 
PDF
Ch7.2-Controls for Programm 001-193819qk
romoeogonzales
 
PPTX
The Magic of WPF & MVVM
Abhishek Sur
 
PPTX
Introduction to XAML and its features
Abhishek Sur
 
PDF
Tool Development 10 - MVVM, Tool Chains
Nick Pruehs
 
KEY
WPF Binding
LearnNowOnline
 
KEY
WPF: Working with Data
LearnNowOnline
 
PDF
Windows App Development Online Training.pdf
SpiritsoftsTraining
 
PDF
04.Navigation on Windows Phone
Nguyen Tuan
 
PPTX
My XML is Alive! An Intro to XAML
Jeremy Likness
 
PPTX
Building Your First Store App with XAML and C#
Tamir Dresher
 
PPTX
Architecting WPF Applications
Paul Stovell
 
PPTX
Silverlight week5
iedotnetug
 
PPT
WPF and Databases
Doncho Minkov
 
PPTX
Data Bondage in WPF
Bruce Johnson
 
PPT
Simple Data Binding
Doncho Minkov
 
PPT
2 Day - WPF Training by Adil Mughal
Adil Mughal
 
PPT
MSDN Unleashed: WPF Demystified
Dave Bost
 
PPTX
Xaml programming
Senthamil Selvan
 
Complex Data Binding
Doncho Minkov
 
WPF - Controls &amp; Data
Sharada Gururaj
 
Ch7.2-Controls for Programm 001-193819qk
romoeogonzales
 
The Magic of WPF & MVVM
Abhishek Sur
 
Introduction to XAML and its features
Abhishek Sur
 
Tool Development 10 - MVVM, Tool Chains
Nick Pruehs
 
WPF Binding
LearnNowOnline
 
WPF: Working with Data
LearnNowOnline
 
Windows App Development Online Training.pdf
SpiritsoftsTraining
 
04.Navigation on Windows Phone
Nguyen Tuan
 
My XML is Alive! An Intro to XAML
Jeremy Likness
 
Building Your First Store App with XAML and C#
Tamir Dresher
 
Architecting WPF Applications
Paul Stovell
 
Silverlight week5
iedotnetug
 
WPF and Databases
Doncho Minkov
 
Data Bondage in WPF
Bruce Johnson
 
Simple Data Binding
Doncho Minkov
 
2 Day - WPF Training by Adil Mughal
Adil Mughal
 
MSDN Unleashed: WPF Demystified
Dave Bost
 
Xaml programming
Senthamil Selvan
 
Ad

Recently uploaded (20)

PPTX
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
PDF
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PPTX
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
COMPARISON OF RASTER ANALYSIS TOOLS OF QGIS AND ARCGIS
Sharanya Sarkar
 
Chris Elwell Woburn, MA - Passionate About IT Innovation
Chris Elwell Woburn, MA
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Q2 FY26 Tableau User Group Leader Quarterly Call
lward7
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
"AI Transformation: Directions and Challenges", Pavlo Shaternik
Fwdays
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
July Patch Tuesday
Ivanti
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
AUTOMATION AND ROBOTICS IN PHARMA INDUSTRY.pptx
sameeraaabegumm
 
Ad

Configuring Data Binding part2 ABTO Software Lecture Korotchyn

  • 1. Windows Application Development with Microsoft .NET Framework 4 Configuring Data Binding 1. Binding to Data Sources (brief overview of the previous lecture) 2. Manipulating and Displaying Data by Oleksiy Korotchyn
  • 2. Binding an Item Control to a List <ListBox ItemsSource="{Binding Source={StaticResource myCollection}}" DisplayMemberPath="FirstName" /> myCollection can be: 2  Simple array  Collection  ADO.NET Object  ObjectDataProvider  XmlDataProvider
  • 3. Binding a Single Property to a List  To show Items Collection (ToString()) <Label Content="{Binding }"/>  To show Current item: <Label Content="{Binding /}"/> 3
  • 4. Binding to Hierarchical Data  For ADO.NET object: <Label Content="{Binding Path=ProductTypes/TypesCategoriesRelation/CategoryName.Length}" /> <!– Table /Relation /Row .Property -->  For array of objects: <Label Content="{Binding /PropertyObject.PropertyObject.MyProperty}"/> <Label Content="{Binding Path=PropertyObject.PropertyObject.MyProperty}"/> 4
  • 5. Navigating a Collection or List To get a reference to ICollectionView: System.ComponentModel.ICollectionView myView; myView = CollectionViewSource.GetDefaultView(myCollection); 5
  • 6. Binding to an Object with ObjectDataProvider 1) IsAsynchronous – indicates whether object creation and method calls are performed on the foreground thread or on a background thread. 2) ObjectInstance – gets or sets the object used as the binding source.  Let’s see example 6
  • 7. Windows Application Development with Microsoft .NET Framework 4 Configuring Data Binding 1. Binding to Data Sources 2. Manipulating and Displaying Data by Oleksiy Korotchyn
  • 8. Data Templates <DataTemplate> <StackPanel> <TextBlock>Company Name:</TextBlock> <TextBlock Text="{Binding CompanyName}" /> <Label Content="{Binding Path=ContactName}"/> </StackPanel> </DataTemplate> 8
  • 9. Data Templates Setting the Data Template <Label> <Label.ContentTemplate> <DataTemplate> <!--Actual data template omitted--> </DataTemplate> </Label.ContentTemplate> </Label> 9
  • 10. Setting the Data Template  Note that for item controls, the DisplayMemberPath and ItemTemplate properties are mutually exclusive. (you can set one but not the other) 10
  • 11. Using Converters to Apply Conditional Formatting in Data Templates [ValueConversion(typeof(DateTime), typeof(Brush))] public class DateBrushConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { … } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } 11
  • 12. Using DataTemplateSelector  The DataTemplateSelector class enables you to assign data templates dynamically to collection objects based on the content of the data. 12
  • 13. Using DataTemplateSelector public class DateDataTemplateSelector : DataTemplateSelector { public override DataTemplate SelectTemplate(object item, DependencyObject container) { FrameworkElement element = container as FrameworkElement; if (element != null && item != null && item is System.Data.DataRowView) {return element.FindResource("BasicTemplate") as DataTemplate; } return null; }} 13
  • 14. Using DataTemplateSelector <Window x:Class="MainWindow" … <Window.Resources> <my:DateDataTemplateSelector x:Key="myTemplateSelector" /> </Window.Resources> <ListBox ItemTemplateSelector="{StaticResource myTemplateSelector}" /> </Window> 14
  • 16. Using Hierarchical Data Templates Item-Related Properties of HierarchicalDataTemplate: 1) ItemBindingGroup – gets or sets the BindingGroup property that is copied to each child item. 2) ItemContainerStyle – gets or sets the Style property that is applied to the item container for each child item. 3) ItemContainerStyleSelector – gets or sets custom style-selection logic for a style that can be applied to each item container. 4) ItemsSource – gets or sets the binding for this data template, which indicates where to find the collection that represents the next level in the data hierarchy 16
  • 17. Using Hierarchical Data Templates Item-Related Properties of HierarchicalDataTemplate: 5) ItemStringFormat – gets or sets a composite string that specifies how to format the items in the next level in the data hierarchy if they are displayed as strings. 6) ItemTemplate – gets or sets the data template to apply to the ItemTemplate property on a generated HeaderedItemsControl control (such as MenuItem or TreeViewItem) to indicate how to display items from the next level in the data hierarchy. 7) ItemTemplateSelector – gets or sets DataTemplateSelector to apply to the ItemTemplateSelector property on a generated HeaderedItemsControl control (such as MenuItem or TreeViewItem) to indicate how to select a template to display items from the next level in the data hierarchy 17
  • 18. Using Hierarchical Data Templates  Let’s see example 18
  • 19. Sorting Data  Bound data can be sorted through the default ICollectionView element for the data list 19
  • 20. Sorting Data System.ComponentModel.ICollectionView myView; myView = CollectionViewSource.GetDefaultView(myCollection); myView.SortDescriptions.Add(new System.ComponentModel.SortDescription("LastName", System.ComponentModel.ListSortDirection.Ascending)); 20
  • 22. Applying Custom Sorting public class MyComparer : System.Collections.IComparer { public int Compare(object x, object y) { Employee empX = (Employee)x; Employee empY = (Employee)y; return empX.LastName.Length.CompareTo(empY.LastName.Length); } } 22
  • 23. Applying Custom Sorting System.ComponentModel.ICollectionView myView; myView =(ListCollectionView)CollectionViewSource.GetDefaultView(myCollection); myView.CustomSort = new MyComparer(); 23
  • 24. Grouping System.ComponentModel.ICollectionView myView; myView = CollectionViewSource.GetDefaultView(myCollection); myView.GroupDescriptions.Add(new PropertyGroupDescription("EmployeeTitle")); 24
  • 25. Grouping Properties of GroupStyle:  ContainerStyle – gets or sets the style applied to the GroupItem object generated for each item  ContainerStyleSelector – represents an instance of StyleSelector that determines the appropriate style to use for the container  HeaderTemplate – gets or sets the template used to display the group header  HeaderTemplateSelector – represents an instance of StyleSelector that determines the appropriate style to use for the header  Panel – gets or sets a template that creates the panel used to layout the items 25
  • 26. Creating Custom Grouping  To create a custom group, you must create a class that implements the IValueConverter interface, which exposes two methods: Convert and ConvertBack. 26
  • 27. Creating Custom Grouping System.ComponentModel.ICollectionView myView; myView = CollectionViewSource.GetDefaultView(myCollection); myView.GroupDescriptions.Add(new PropertyGroupDescription("Region", new RegionGrouper())); 27
  • 28. Filtering Data System.ComponentModel.ICollectionView myView; myView = CollectionViewSource.GetDefaultView(myItems); myView.Filter = new Predicate<object>(myFilter); 28
  • 29. Filtering Data public bool myFilter(object param) { return (param.ToString().Length > 8); } 29
  • 30. Filtering ADO.NET Objects The filter expression is a string expression in the following format: <ColumnName> <Operator> <Value> BindingListCollectionView myView; myView = (BindingListCollectionView)CollectionViewSource.GetDefaultView(myItems); myView.CustomFilter = "Sandwich = 'Muffaletta'"; 30
  • 31. Filtering, Grouping and Sorting  Let’s see example 31