Update Silverlight TextBox Binding Source OnChange
Problem
By default any binding for a TextBox is not updated until the field loses focus. This didn’t suit my needs for an application I’m currently working on because I wanted the Binding source to be updated whenever something is entered into the TextBox. With WPF this is done easily by setting the UpdateSourceTrigger property to PropertyChanged in the Binding definition, unfortunately this is not available for Silverlight.
The Solution
A workaround that I found for this was to add a KeyUp event to the required TextBox and update the binding in code behind.
The Code
For example if you had the following TextBox declared in your XAML file:
<TextBox Text="{Binding Path=ClientName, Mode=TwoWay}" Name="tbName"/>
You could add the following to your code behind file:
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
public MyUserControl()
{
InitializeComponent();
tbName.KeyDown += new KeyEventHandler(tbName_KeyUp);
}
private void tbName_KeyUp(object sender, KeyEventArgs e)
{
BindingExpression binding = (sender as TextBox).GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
}
Since the above is not dependent on any particular TextBox or ViewModel it could be changed to a custom TextBox control that auto-updates on KeyUp, for example:
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
public class AutoUpdateTextBox : TextBox
{
protected override void OnKeyUp(KeyEventArgs e)
{
BindingExpression binding = this.GetBindingExpression(TextBox.TextProperty);
binding.UpdateSource();
base.OnKeyUp(e);
}
}
This would then be used in XAML like a standard TextBox:
<my:AutoUpdateTextBox Text="{Binding Path=ClientName, Mode=TwoWay}"/>
Key Points
- Firstly we use the FrameworkElement.GetBindingExpression(), passing in the TextBox.TextProperty DependencyProperty to get the BindingExpression object, which contains information about the textboxes Binding.
- We then call the UpdateSource() method to update the Binding’s source property.