In this article, we are going to learn about Different types of Data Binding Techniques in Silverlight and how to validate Data in SilverLight.
Different types of Data Binding in Silverlight
The data binding in Silverlight is achieved using Binding class
Binding in Silverlight
1. OneTime
– The data is set when Binding is initialized – mostly used in ReadOnly mode.
2. OneWay
– Updates data from source to target, so if source changes the target is notified (Default if not specified)
3. TwoWay
– Updates data from source to target and vice-versa, so if source changes the target is notified or vice versa.
This article is the continuation of my last article in Silverlight controls series, read last article here.
Get 500+ ASP.NET web development Tips & Tricks and ASP.NET Online training here.
Based on our need in the project, we need to decide that which type of binding we want to work with.
How to work with TwoWay binding or INotifyPropertyChnaged interface?
In case we want to reflect the source while changing the target value or vice-versa, we need to work with TwoWay binding
.
Code
<Canvas>
<TextBlock Text="FirstName" Canvas.Top="20" Canvas.Left="20"/>
<TextBox x:Name="FirstName" Text="{Binding FirstName, Mode=TwoWay}" Width="150" Canvas.Top="20" Canvas.Left="100" />
<TextBlock Text="LastName" Canvas.Top="60" Canvas.Left="20"/>
<TextBox x:Name="LastName" Text="{Binding LastName, Mode=TwoWay}" Width="150" Canvas.Top="60" Canvas.Left="100" />
</Canvas>
In the above code, notice that we have Text property of the TextBox as Binding and Mode as TwoWay.
In order to work with TwoWay binding to achieve change notification in either direction, we need to inherit our Entity class (Business object) with INotifyPropertyChanged
interface that contains a PropertyChanged
event that needs an implementation.
Code behind
public INotifyChangeSample()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MethodToLoadData);
}
void MethodToLoadData(object sender, RoutedEventArgs e)
{
Person p = new Person();
p.FirstName = "Sheo";
p.LastName = "Narayan";
LayoutRoot.DataContext = p;
}
public class Person : INotifyPropertyChanged
{
string _firstName = string.Empty;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
InitiatePropertyChanges("FirstName");
}
}
string _lastName = string.Empty;
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
InitiatePropertyChanges("LastName");
}
}
public event PropertyChangedEventHandler PropertyChanged;
void InitiatePropertyChanges(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
When the page loads, MethodToLoadData
executes and sets the DataContext
of the Grid to the Person object. As both TextBoxes Text property are set to Binding so both TextBoxes gets populated with the FirstName and LastName data respectively.
You must have noticed that we are inheriting Person class with INotifyPropertyChnaged event so we need to implement Event PropertyChanged
that’s what we have done.
In every property setter after setting the property value we are calling InitiatePropertyChanges
method by passing the Property name that ultimately calls the PropertyChanged event and updates its source or target accordingly.
(Start this page in Debug mode and step through the code to understand it clearly)
Output

Validating data in Silverlight
Silverlight supports data validation by its data binding framework while data binding. This can be done in TwoWay binding. Binding object supports ValidatesOnExceptions
and NotifyOnValidationError
property that let us validate the data.
How to validate the data in Silverlight using Binding framework?
Binding framework of Silverlight has very handy properties to validate the data while entering the data. We can control the control behaviour for which validation has failed using BindingValidationError
event.
Code
<Grid x:Name="LayoutRoot" Background="White" BindingValidationError="LayoutRoot_BindingValidationError">
<Canvas>
<TextBlock Text="Name" Margin="10"/>
<TextBox Text="{Binding MyName}" x:Name="txtFirstName" Width="150" Height="25" Canvas.Left="50" Canvas.Top="10" />
<TextBlock Text="Age" Canvas.Top="40" Canvas.Left="10"/>
<TextBox Text="{Binding MyAge, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" x:Name="txtLastName" Width="150" Height="25" Canvas.Left="50" Canvas.Top="40" />
<Button Content="Submit" Canvas.Top="70" Canvas.Left="100" Click="Button_Click" />
</Canvas>
</Grid>
In the above code snippet we have handled BindingValidationError
event for the Grid as we are going to keep all our TextBox controls inside it that is going to validate the data at the time of data entry. Keeping BindingValidationError
to the Grid let us control all validation failed error within the Grid.
Under the Grid, we have a Name TextBox and Age TextBox. We want to validate the Age TextBox as there is a chance that user might enter string data instead of integer. To validate the Age text box we have specified Binding mode as “TwoWay
” (Validation works only in TwoWay binding), set ValidatesOnExceptions
property to true (this enable validation of the data) and NotifyOnValidationError
property to true (this will raise the BindingValidationError event of the control or its parent control, in this case Grid).
As you can see that on BindingValidationError
event we have set LayoutRoot_BindingValidationError
method to be called.
Code behind
private void LayoutRoot_BindingValidationError(object sender, ValidationErrorEventArgs e)
{
if (e.Action == ValidationErrorEventAction.Added)
{
MessageBox.Show("Sorry, error occured." + e.Error.Exception);
TextBox textbox = e.OriginalSource as TextBox;
textbox.Background = new SolidColorBrush(Colors.Red);
textbox.Foreground = new SolidColorBrush(Colors.White);
}
else
{
TextBox textbox = e.OriginalSource as TextBox;
textbox.Background = new SolidColorBrush(Colors.White);
textbox.Foreground = new SolidColorBrush(Colors.Green);
}
}
When user tries to enter alphabets into the Age TextBox and press tab or click mouse outside the TextBox, validation occurs and it provides the error as you can see in below output.
If we want to customize the error, we can use LayoutRoot_BindingValidationError
method that has been attached with BindingValidationError
of the Grid. When an error occurs, the Action property of ValidationErrorEventArgs
gets updated with ValidationErrorEventAction.Added
and if the error gets resolved it gets updated with ValidationErrorEventAction.Removed
.
Based on the ValidationErrorEventArgs
’s Action state we have changed the background color and foreground color of the TextBox.
Output

Hope this article was useful. Thanks for reading and hoping that you liked it.
Keep an eye on forth coming articles on Silverlight. To read my series of articles,click here.