Can you explain one way and two way bindings?

 Posted by ArticlesMaint on 9/23/2009 | Category: Silverlight Interview questions | Views: 2922


One way binding


As the name so the behavior. In one way bindings data flows only from object to UI and not vice-versa. For instance you can have a textbox called as ‘TxtYear’ which is binded with an object having property ‘Year’. So when the object value changes it will be reflected on the silverlight UI, but the UI cannot update the year property in the object.



 


 


 


 


 


It’s a three step procedure to implement one way binding. First create your class which you want to bind with the silverlight UI.  For instance below is a simple class called as ‘ClsDate’ with a ‘Year’ property.

public class clsDate

{
private int _intYear;
public int Year
{
set
{
_intYear = value;
}
get
{
return _intYear;
}
}
}

In the second step you need to tie up the ‘Year’ property with a silver light UI text box. To bind the property you need to specify ‘Binding Path=Year’ in the text property of the text box UI object. ‘Year’ is the property which we are binding with the text box UI object.

<TextBox x:Name="txtCurrentYear" Text="{Binding Path=Year}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>


The final step is to bind the text box data context with the date object just created.

public partial class Page : UserControl

{
public Page()
{
InitializeComponent();
clsDate objDate = new clsDate();
objDate.Year = DateTime.Now.Year;
txtCurrentYear.DataContext = objDate;
}
}

Two way binding


Two way binding ensure data synchronization of data between UI and Objects. So any change in object is reflected to the UI and any change in UI is reflected in the object.



 


 


 


 


 



To implement two way binding there are two extra steps with addition to the steps provided for ‘OneWay’.  The first change is we need to specify the mode as ‘TwoWay’ as shown in the below XAML code snippet.

<TextBox x:Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" VerticalAlignment="Center" HorizontalAlignment="Center"></TextBox>

Second change is we need to implement ‘INotifyPropertyChanged’ interface. Below is the class which shows how to implement the ‘INotifyPropertyChanged’ interface. Please note you need to import ‘System.ComponentModel’ namespace.

public class clsDate : INotifyPropertyChanged

{
public event PropertyChangedEventHandler PropertyChanged;
private int _intYear;
public int Year
{
set
{
_intYear = value;
OnPropertyChanged("Year");
}
get
{
return _intYear;
}
}
private void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this,new PropertyChangedEventArgs(property));
}
}}

The binding of data with data context is a compulsory step which needs to be performed.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response