Data binding has evolved over the years. Silverlight, for example, offers robust data binding capabilities. With Silverlight, you’ll use the BindingExpression.UpdateSource method to control exactly when the data source is updated. Here, we’ll describe one such scenario in which we are explicitly updating the data source.

 

You have a single text box on your Silverlight screen, with some validation tied to it. On the same screen, you’ll have a “next” button. When you click on that next button, controls on the page are destroyed and created again, due to some business logic.

 

Let’s continue on with this scenario. You hit the “next” button. Validation doesn’t fire, and takes you to the next screen.

 

So, what went wrong?

 

Suppose I have a text box inside a user control.

 

<UserControl x:Class=”TextboxQuestionPane”…….

<TextBox x:Name=”txtAnswer” …. >

<TextBox.Text>

<Binding Mode=”TwoWay” Path=”Response” NotifyOnValidationError=”True” ValidatesOnExceptions=”True” />

</TextBox.Text>

</TextBox>

</UserControl>

 

We are setting the DataContext of Textbox, and setting the source property “Response” in the loaded event of the containing User Control. Validation is performed on the setter of the Response property.

 

void TextboxQuestionPane_Loaded(object sender, RoutedEventArgs e)

{

MyFieldValidation validation = new MyFieldValidation()validation.Response = “Hello World”;

txtAnswer.DataContext = validation;

}

public class MyFieldValidation : INotifyPropertyChanged

{

public string Response

{

get { return response; }

set

{

response = value;

Validate();//Performs the custom validation

RaisePropertyChangedEvent(“Response”);

}

}

}

 

Again – why isn’t the validation firing on clicking the “next” button?

 

The answer is TextBox. Text property has a default UpdateSourceTrigger value of LostFocus; this means if an application has a TextBox with a data-bound TextBox.Text property, the text you type into the TextBox does not update the source until the TextBox loses focus.

 

In this case, when you are clicking the “next” button, LostFocus is getting fired, and thus the validation is also getting performed. However, since the controls are destroyed and created again, the end user is not able to see the error message.

 

So, what’s the solution? This problem can be overcome by explicitly updating the source, with the help of the BindingExpression.UpdateSource method.

BindingExpression exp = txtAnswer.GetBindingExpression(TextBox.TextProperty);

if (exp != null) exp.UpdateSource();

try

{

.

if (txtAnswer.DataContext is TextFieldValidation)

{

((TextFieldValidation)txtAnswer.DataContext).Validate();

}

……..

}

catch

{

//Avoid the Navigation to the next screen

}

 

Abhishek
Abhishek
Sr. Technical Consultant