Skip to content

Instantly share code, notes, and snippets.

@jgable
Created February 28, 2011 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jgable/847504 to your computer and use it in GitHub Desktop.
Save jgable/847504 to your computer and use it in GitHub Desktop.
Updates a source binding for a TextBox when the text changes and not just when the box loses focus.
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Interactivity;
public class UpdateSourceOnTextChanged : Behavior<TextBox>
{
BindingExpression textBinding;
protected override void OnAttached()
{
if (this.AssociatedObject == null)
return;
// Get the binding
textBinding = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
// Subscribe to text changed events.
this.AssociatedObject.TextChanged += AssociatedObject_TextChanged;
base.OnAttached();
}
void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e)
{
// Update the binding source.
if(textBinding != null)
textBinding.UpdateSource();
}
protected override void OnDetaching()
{
if (this.AssociatedObject == null)
return;
// Clean up...
this.textBinding = null;
this.AssociatedObject.TextChanged -= AssociatedObject_TextChanged;
base.OnDetaching();
}
}
<TextBox
Text="{Binding SomeTextProperty, Mode=TwoWay}">
<i:Interaction.Behaviors>
<con:UpdateSourceOnTextChanged />
</i:Interaction.Behaviors>
</TextBox>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment