Created
February 28, 2011 15:52
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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