0% found this document useful (0 votes)
33 views13 pages

1.3 9 - DataBinding PDF

Uploaded by

So
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views13 pages

1.3 9 - DataBinding PDF

Uploaded by

So
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Deccansoft Software Services – WPF Data Binding

Agenda: Dat aBinding

Overview
What is Databinding?
Databinding Syntax
Data Binding to Custom Objects
Multibinding / Formatted String
Data Biding to Collection of Object
Data Template
Programming with CollectionView

Validating Items
XML Data Provider
Object Data Provider
Working with DataGrid

Overview

W indows Presentation Foundation (WPF) data binding provides a simple and consistent way for applications to
present and interact with data. Elements can be bound to data from a variety of data sources in the fo rm of
common language runtime (CLR) objects and XML .

The data binding functionality in WPF has several adva ntages over traditional models,
o A broad range of properties that inherently support data binding,
o Flexible UI representation of data,
o Clean separation of business logic from UI.

What is Databinding ?
Data binding is the process that establishes a connection between the application UI and business logic. If the
binding has the correct settings and the data provides the proper notifications, then, wh en the data changes its
value, the elements that are bound to the data reflect changes automatically.
Data binding can also mean that if an outer representation of the data in an element changes, then the
underlying data can be automatically updated to reflect the change. For example, if the user edits the value in
a TextBox element, the underlying data value is automatically updated to reflect that change.

In WPF, dependency properties of elements can be bound to CLR objects (including ADO.NET objects or o bjects
associated with Web Services and Web properties) and XML data.

Databinding Syntax

• Typically, each binding has these four components: a binding target object, a target property, a binding source,
and a path to the value in the binding source to use. For example, if you want to bind the content of a TextBox
to the Name property of an Employee object, your target object is the Tex tBox, the target property is the Text
1
Deccansoft Software Services – WPF Data Binding

property, the value to use is Name, and the source object is the Employee object.
• The target be a property must dependency property. Most UIElement proper ties are dependency properties
and most dependency properties, except read-only ones, support data binding by default
Simple Element – Element Binding
<Slider Name="fontSizeSlider" Minimum="5" Maximum="100" Value="10" Grid.Row="0" />
<TextBox Tex t="{Binding ElementName=fontSizeSlider,Path=Value }" />
<TextBlock Grid.Row="1 ">
<TextBlock.Text>
<Binding ElementName="fontSizeSlider" Path="Text"/>
</TextBlock.Text>
</TextBlock>

Direction of the DataFlow:


You may want your application to enable users to change the data and propagate it back to the source object. Or
you may not want to enable users to update the source data. You can control this by setting the Mode property of
your Binding object.
The following are the different types of data flow and are possible values for Mode property of Binding:
• OneWay binding causes changes to the source property to automatically update the target property, but
changes to the target property are not propagated back to the source property. This type of binding is
appropriate if the control being bound is implicitly read-only.
• TwoWay binding causes changes to either the source property or the target property to automatically update
the other. This type of binding is appropriate for editable forms or other fully-interactive UI scenarios. Most
properties default to OneWay binding, but some dependency properties (typically properties of user -editable
controls such as the Text proper ty of Tex tBox and the IsChec ked property of CheckBox) default to TwoWay
binding.
• OneWayToSour ce is the reverse of OneWay binding; it updates the source property when the target property
changes. One example scenario is if you only need to re-evaluate the source value from the UI.
• OneTime binding, which causes the source property to initialize the target property, but subsequent changes
do not propagate. This means that if the data context undergoes a change or the object in the data context
changes, then the change is not reflected in the target property.
Example
<Slider Name="fontSizeSlider" Minimum="5" Maximum="100" Value="10" Grid.Row="0" />
<TextBox Tex t="{Binding ElementName=fontSizeSlider,Path=Value , Mode =TwoWay}" />

UpdateSource Trigger Property:


Bindings that are TwoWay or OneWayToSource listen for changes in the target property and propagate them back
to the source. This is known as updating the source. For example, you may edit the text of a TextBox to change the
underlying source value. As described in the last section, the direction of the data flow is determined by the value
2
Deccansoft Software Services – WPF Data Binding

of the Mode property of the binding


However, does your source value get updated while you are editing the tex t or after you finish editing the text and
point your mouse away from the TextBox? The UpdateSourceTrigger property of the binding determines what
triggers the update of the source.
UpdateTrigger property takes three values. They are
PropertyChanged
LostFocus
Explicit
Default value of UpdateSourceTrigger depends on the control. While PropertyChanged is fine for CheckBoxes and
other simple controls. For text fields, updating after every keystroke can diminish performance and it denies the
user the usual opportunity to backspace and fix typing errors before committing to the new value. That is wh y the
Text property has a default value of LostFocus instead of PropertyChanged.
<Slider Name="fontSizeSlider" Minimum="5" Maximum="100" Value="10" Grid.Row="0" />
<TextBox Name="SizeTextBox" Tex t="{Binding ElementName=fontSizeSlider,Path=Value, Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}" />

Data Binding to Custom Objects (that aren’t Elements)

So far, you’ve focused on adding bindings that link two elements. But in data -driven applications, it’s more common
to create binding expressions that draw their data from a nonvisual object. The only requirement is that the
information you want to display must be stored in public properties. The WPF data binding infrastructure won’t pick
up private information or public fields.

When binding to an object that isn’t an element, you need to give up the Binding.Element-Name property and use
one of the following properties instead:
Source. This is a reference that points to the source object.
RelativeSource . This points to the source object using a RelativeSource object, which allows you to base your
reference on the current element. This is a specialized tool that’s handy when writing control templates and data
templates.
• DataContext. If you don’t specify a source using the Source or RelativeSource property, WPF searches up the
element tr ee starting at the current element. It examines the Data -Context property of each element and uses the
first one that isn’t null. The DataContext property is extremely useful if you need to bind several properties of the
same object to different elements, because you can set the DataContext property of a higher -level container object
rather than directly on the target element.
public class Employee : INotifyPropertyChanged
{
int _employeeNumber;
string _firstName;

3
Deccansoft Software Services – WPF Data Binding

string _lastName;
string _department;
string _title;
public event PropertyChangedEventHandler PropertyChanged;
public Employee()
{
_employeeNumber = 0;
_firstName =
_lastName =
_department =
_title = null;
}
public int EmployeeNumber
{
get { return _employeeNumber ; }
set
{
_employeeNumber = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("EmployeeNumber"));
}
}
public string FirstName
{
get { return _firstName; }
set
{
_firstName = value;
if (PropertyChanged != null)
PropertyChanged( this, new PropertyChangedEventArgs("FirstName"));
}
}
public string LastName
{
get { return _lastName; }
set
{
_lastName = value;
4
Deccansoft Software Services – WPF Data Binding

if (PropertyChanged != null)
PropertyChanged( this, new PropertyChangedEventArgs("LastName"));
}
}
public string Department
{
get { return _department; }
set
{
_department = value;
if (PropertyChanged != null)
PropertyChanged( this, new PropertyChangedEventArgs("Department"));
}
}

public string Title


{
get { return _title; }
set
{
_title = value;
if (PropertyChanged != null)
PropertyChanged( this, new PropertyChangedEventArgs("Title"));
}
}
}

<Window.Resources>
<local:Employee x:Key="MyEmployee" EmployeeNumber="123" FirstName="John" LastName="Doe"
Department="Product Development" Title="QA Manager" />
</Window.Resources>
<!-- Binding using Source -->
<TextBox Text="{Binding Path=EmployeeName, Source={StaticResource MyEmployee}}"/>
<!-- Binding using DataContext-->
<StackPanel DataContext="{StaticResource MyEmployee}">
<Label>Employee Number</Label>
<TextBox Tex t="{Binding Path=EmployeeNumber}"></TextBox>
<Label>First Name</Label>
5
Deccansoft Software Services – WPF Data Binding

<TextBox Tex t="{Binding Path=FirstName}"></TextBox >


<Label>Last Name</Label>
<TextBox Tex t="{Binding Path=LastName}" />
<Label>Title</Label>
<TextBox Tex t="{Binding Path=Title}"></TextBox >
<Label>Department</Label>
<TextBox Tex t="{Binding Path=Department}" />
</Grid>

<!-- Binding with Formated String -->


<TextBlock DataContext="{StaticResource stud1}">
<TextBlock.Text>
<MultiBinding StringFormat="Name={1}, {0}">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>

Data Biding to Collection of Object

We can bind List Controls like ListBox and ComboBox to collection of Objects. On doing so for each object of the
collection object an item will be item added to the List control.
public class EmployeeList : List<Employee>
{
}
<Window.Resources>
<local:EmployeeList x:Key="myEmployeeList">
<local:Employee EmployeeNumber="1" FirstName="John" LastName="Dow" Title="Accountant"
Department="Payroll" />
<local:Employee EmployeeNumber="2" FirstName="Jane" LastName="Austin" Title="Account Ex ecutive"
Department="Customer Management" />
<local:Employee EmployeeNumber="3" FirstName="Ralph" LastName="Emmerson" Title="QA Manager"
Department="Product Development" />
<local:Employee EmployeeNumber="4" FirstName="Patrick" LastName="Fitzgerald" Title="QA Manager"
Department="Product Development" />
<local:Employee EmployeeNumber="5" FirstName="Charles" LastName="Dickens" Title="QA Manager"
Department="Product Development" />
</local:EmployeeList>
6
Deccansoft Software Services – WPF Data Binding

<local:Employee x:Key="E1 " EmployeeNumber="1" FirstName="John" LastName="Dow" Title="Accountant"


Department="Payroll" />
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource myEmployeeList}}">

<ListBox Name="employeeListBox" ItemsSource="{Binding Source={StaticResource myEmployeeList}}" />


<Grid Grid.Row="1" DataContext="{Binding ElementName=employeeListBox, Path=SelectedItem}">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0">First Name</Label>
<Label Grid.Row="1" Grid.Column="0">Last Name</Label>
<Label Grid.Row="2" Grid.Column="0">Title</Label>
<Label Grid.Row="3" Grid.Column="0">Department</Label>

<TextBox Grid.Row="0 " Grid.Column="1" Text="{Binding Path=FirstName}" />


<TextBox Grid.Row="1 " Grid.Column="1" Text="{Binding Path=LastName}" />
<TextBox Grid.Row="2 " Grid.Column="1" Text="{Binding Path=Title}" />
<TextBox Grid.Row="3 " Grid.Column="1" Text="{Binding Path=Department}" />
</Grid>

Data Template

<ListBox Name="lstStudents1" ItemsSource="{Binding Source={StaticResource myEmployeeList}}">


<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<TextBlock Text="{Binding Path=FirstName}"/>
(Department=<TextBlock Tex t="{Binding Path=Department}"/>)
</TextBlock>
</DataTemplate>
7
Deccansoft Software Services – WPF Data Binding

</ListBox.ItemTemplate>
</ListBox>
Or
<Window.Resources>
<DataTemplate Dat aType="{x:Type local:Employee}">
<TextBlock>
<TextBlock Text="{Binding Path=FirstName}"/>
(Department=<TextBlock Tex t="{Binding Path=Department}"/>)
</TextBlock>
</Dat aTemplate>
</Window.Resources>

<ListBox Name="employeeListBox" ItemsSource="{Binding Source={StaticResource myEmployeeList}}" />

Programming with IColle ctionView

<ListBox IsSynchronizedWithCurrentItem="True" Name="employeeListBox"


DataContext="{DynamicResource myEmployeeList}" ItemsSource="{Binding}" />

Navigating between Items


private void btnMovePrevious_Click(object sender, RoutedEventArgs e)
{
EmployeeList emp = (EmployeeList)this.FindResource("myEmployeeList");
ICollectionView view = CollectionViewSource.GetDefaultView(studs);
view.MoveCurrentToPrevious();
if (view.IsCurrentBeforeFirst)
view.MoveCurrentToFirst();
}
private void btnMoveNext_Click(object sender, RoutedEventArgs e)
{
EmployeeList studs = (EmployeeList)this.FindResource("myEmployeeList");
ICollectionView view = CollectionViewSource.GetDefaultView(studs);
view.MoveCurrentToNext();
if (view.IsCurrentAfterLast)
view.MoveCurrentToLast();
}
Sorting Items in Collection
private void btnSort_Click(object sender, RoutedEventArgs e)
{
EmployeeList emps = (EmployeeList)this.FindResource("myEmployeeList");
8
Deccansoft Software Services – WPF Data Binding

ICollectionView view = CollectionViewSource.GetDefaultView(emps);


if (view.SortDescriptions.Count == 0)
view.SortDescriptions.Add(new SortDescription("FirstName", ListSortDirection.Ascending));
else
view.SortDescriptions.Clear();
}
Filtering Items in Collection
private void btnFilter_Click(object sender, RoutedEventArgs e)
{
EmployeeList emps = (EmployeeList)this.FindResource("myEmployeeList");
ICollectionView view = CollectionViewSource.GetDefaultView(emps);
view.Filter += delegate(object item)
{
return (((Employee)item).Department == "Product Development");
};
}
Adding Items to Collection
public class EmployeeList : ObservableCollection<Employee>
{
}

private void btnAddEmployee_Click(object sender, RoutedEventArgs e)


{
ObservableCollection<Employee> oc = Resources["myEmployeeList"] as ObservableCollection<Employee>;

Employee emp = new Employee() { EmployeeNumber = 5, FirstName = "Kate", LastName = "Darwin",


Department = "Test Engineer", Title = "Manager" };
oc.Add(emp);
}

Validating Items

Edit the set block of Property and if the validation fails, throw the Runtime Exception.
public string FirstName
{
get { return _firstName; }
set
{
if (value == "")
9
Deccansoft Software Services – WPF Data Binding

throw new ApplicationException("Enter a value");


_firstName = value;
OnPropertyChanged("FirstName");
}
}
<TextBox >
<TextBox .Text>
<Binding Path="FirstName" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<ExceptionV alidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox >

Object Data Provider

public class EmployeesLoader


{
public EmployeeList GetAllEmployees()
{
//return (EmployeeList)App.Current.MainWindow.Resources["myEmployeeList"];
EmployeeList lst = new EmployeeList()
{
new Employee(){EmployeeNumber=1,FirstName="EF1",LastName="EL1",Title="T1",Department="D1"},
new Employee(){EmployeeNumber=2,FirstName="EF2",LastName="EL2",Title="T2",Department="D1"},
new Employee(){EmployeeNumber=3,FirstName="EF3",LastName="EL3",Title="T3",Department="D2"},
new Employee(){EmployeeNumber=4,FirstName="EF4",LastName="EL4",Title="T4",Department="D2"},
new Employee(){EmployeeNumber=5,FirstName="EF5",LastName="EL5",Title="T5",Department="D2"},
};
return lst;
}
}
Add the following in Window.Resour ces
<Obje ctDataProvider x:Key="odpEmployees"
ObjectType="{x :Type local:EmployeesLoader}"
MethodName="GetAllEmployees"
IsAsynchronous="False" />

<ListBox DataContext="{StaticResource odpEmployees}" ItemsSource="{Binding}" >


10
Deccansoft Software Services – WPF Data Binding

</ListBox>
Object Data Sour ce With Method Having Parameters
public IEnumerable<Employee> GetAllEmployeesOfDepartment(string deptName)
{
EmployeeList lst = (EmployeeList)App.Current.MainWindow.Resources["myEmployeeList"];
return lst.Where(emp => emp.Department == deptName);
}
Add the following in Window.Resour ces
<ObjectDataProvider x:Key="odpEmployeesByDepartment"
ObjectType="{x :Type local:EmployeesLoader}"
MethodNa me="GetAllEmployeesOfDepartment"
IsAsynchronous="False">
<ObjectDataProvider.MethodParameters>
<sys:String>D1</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

To progr ammatically change the parameter value


ObjectDataProvider odp = (ObjectDataProvider) this.FindResource("odpEmployeesByDepartment");
odp.MethodParameters[0] = "D2";

XML Data Provider

Employees.Xml
<Employees>
<Employee EmployeeNumber="1 ">
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Title>Accountant</Title>
<Department>Payroll</Department>
</Employee>
<Employee EmployeeNumber="2 ">
<FirstName>Jane</FirstName>
<LastName>Austin</LastName>
<Title>Account Ex ecutive</Title>
<Department>Customer Management</Department>
</Employee>
<Employee EmployeeNumber="3 ">
<FirstName>Ralph</FirstName>
<LastName>Emmerson</LastName>
11
Deccansoft Software Services – WPF Data Binding

<Title>QA Manager</Title>
<Department>Product Development</Department>
</Employee>
</Employees>

XML DataProvider as Resource


<XmlDataProvider Source="Employees.xml" XPath="/Employees/Employee" x:Key="xdpEmployees"/>
<XmlDataProvider x:Key="xdpEmpoyeeDataIsland" XPath="/Employees/Employee">
<x:XData>
<Employees>
<Employee EmployeeNumber="1">
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Title>Accountant</Title>
<Department>Payroll</Department>
</Employee>
<Employee EmployeeNumber="2">
<FirstName>Jane</FirstName>
<LastName>Austin</LastName>
<Title>Account Ex ecutive</Title>
<Department>Customer Management</Department>
</Employee>
<Employee EmployeeNumber="3">
<FirstName>Ralph</FirstName>
<LastName>Emmerson</LastName>
<Title>QA Manager</Title>
<Department>Product Development</Department>
</Employee>
</Employees>
</x:XData>
</XmlDataProvider>

Using XML Dat a Provider


<ListBox IsSynchronizedWithCurrentItem="True"
DataContext="{DynamicResource xdpEmployees}" ItemsSource="{Binding}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
12
Deccansoft Software Services – WPF Data Binding

<TextBlock Text="{Binding XPath=FirstName}"></TextBlock>


<TextBlock Text="{Binding XPath=LastName}"></TextBlock>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

13

You might also like