Here is a simple little behavior for updating a TextBox's Text property in Silverlight when the text changes instead of when it 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> |
Quick and Easy. Gotta Love Behaviors.
Jacob