Thursday, 23 February 2012

Data Binding in WPF(Windows Presentation Foundation).



WPF introduced data binding concept which provides simple and easy way to represent data in application.

Data binding, in the context of .NET, is the method by which controls on a user interface (UI) of a client application are configured to fetch from, or update data into, a data source such as a database or XML document.

Prior to .NET, data binding models limited access to databases. Hence many DBMSs (database management systems) could access the data source indirectly through their API (application programming interface) without any flexibility in controlling the data binding process. This problem is addressed in .NET by providing fine control of how the data is bound and the behavior of UI with Windows Forms and ADO.NET classes in the Framework. The development of web applications is simplified by providing data binding capability to web pages using .NET server-side web controls. 


Data binding establish link between source and target.

As illustrated in the diagram, Binding establish link between source object and target object. When source object updates it notifies target object and when target object updates it notifies source object if binding is set to two way.

Binding object has four major components :
  •   Source object, 
  •   Target object,
  •   Source Property,
  •   Path.
We can specify other properties of binding like Binding Mode, Name etc. 
While binding target property must be a Dependency property.  Almost all UI elements/controls are derived from Dependency object so you can set an element's property as target property of data binding. You can define Binding in XAML file as well in code behind.

Sample code for Binding:
<StackPanel>
   <TextBox Name="txtname" Width="150" Height="35" Text="" />
   <Label Content="{Binding ElementName=txtname, Path=Text}"
          Width="150" Height="35" />
</StackPanel>



Here both properties are dependency properties.  In above example TextBox’s Text property is source of data and Label’s content property is target. Whenever users types something in textbox it will automatically update label’s content.



This is about simple Data binding in WPF.

Happy Binding.