DataBinding In WPF

Data Binding is a mechanism in WPF applications that provides simple and easy way for application to display and interact with data. It allows the flow of data between UI and business model. Any modification done on the data in your business model after binding is done, will automatically reflect to UI, and vice versa.

Binding can be one-directional or bi-directional. The source of databinding can be a normal .NET property or Dependency property, however, target property must be a Dependency property.

For making binding to work properly, both sides of property must provide change in notification which will tell the binding to update the target value. On normal .NET properties, it can be achieved by using INotifyPorpertyChanged interface. And for Dependency properties, it is done by PropertyChanged callback of property metadata.

Databinding is achieved in XAML by using Binding mark-up extension i.e. {Binding}.

Eaxmple

  1. <Window.Resources>  
  2.     <local:Employee x:Key="MyEmployee" EmployeeNumber="123" FirstName="John" LastName="Doe" Department="Product Development" Title="QA Manager" /> </Window.Resources>  
  3. <Grid DataContext="{StaticResource MyEmployee}">  
  4.     <TextBox Text="{Binding Path=EmployeeNumber}"></TextBox>  
  5.     <TextBox Text="{Binding Path=FirstName}"></TextBox>  
  6.     <TextBox Text="{Binding Path=LastName}" />  
  7.     <TextBox Text="{Binding Path=Title}"></TextBox>  
  8.     <TextBox Text="{Binding Path=Department}" />  
  9. </Grid>  

DataContext

Datacontext property is used for setting the data to UI. If you do not explicitly define source of binding, it takes data context by default.

Types Of Binding

  • OneWay
  • TwoWay
  • OneWayToSource
  • OneTime
X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now