How to disable automatic source updates in Silverlight


This article demonstrates how we can disable automatic source updates in Silverlight. In TwoWay bindings, when changes are made to the target, It automatically updates the source, except when we bind Text property of a TextBox. In this case, the update occurs when the TextBox loses focus. Learn how to disable automatic source updates in Silverlight? We can disable automatic source updates and update the source when we would like to.

Find the code to know how to disable automatic source updates in Silverlight?


To disable automatic source updates, we need to set the UpdateSourceTrigger property to Explicit. We must update the source for each binding individually,
Follow below steps to update a binding:

1.First call the FrameworkElement.GetBindingExpression method of a target element, by passing in the target DependencyProperty.

2.Then use the return value to call the BindingExpression.UpdateSource method.

The following example code snippet demonstrates this process.

Here txtDemo is a TextBox with Binding set to the Test property of the TestData class. Observe that the UpdateSourceTrigger property is set to "Explicit".



<TextBox x:Name="txtDemo" Text="{Binding Test, Mode=TwoWay, UpdateSourceTrigger=Explicit}" /><Button Content="Update" Click="Button_Click" />


public class TestData
{
public String Test { get; set; }
}

TestData data;

public MainPage()
{
InitializeComponent();
data = new TestData { Test = "my Data" };
txtDemo.DataContext = data;//Set the DataContext of the TextBox to data, which is an instance of the TestData class.
}

private void Button_Click(object sender, RoutedEventArgs e)
{
//Call the FrameworkElement.GetBindingExpression method of a target element which is "txtDemo", by passing in the target DependencyProperty that is the TextProperty of the TextBox.

BindingExpression expression = txtDemo.GetBindingExpression(TextBox.TextProperty);
MessageBox.Show("Before UpdateSource, Test = " + data.Test);
//use the return value to call the BindingExpression.UpdateSource, This updates the Text Property of the txtDemo Framework Element.
expression.UpdateSource();
MessageBox.Show("After UpdateSource, Test = " + data.Test);
}


Comments

Author: Gaurav Kumar Arora14 Nov 2011 Member Level: Gold   Points : 0

Good and valuable article. Priya also post silverlight resources/articles in Silverlightclub.com a sister site of DNS



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: