1.3 9 - DataBinding PDF
1.3 9 - DataBinding PDF
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>
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"));
}
}
<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
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
Data Template
</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>
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
</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>
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>
13