Update the bound property as the user types

In Silverlight there is no way for 2-way-bound TextBox to update it’s bound property every time user hits a key on the keyboard.

In WPF you could use UpdateSourceTrigger=PropertyChanged, which is not available in Silverlight.

Here’s the nice Silverlight behavior that adds this useful feature to Silverlight:

// Please note that Behavior class is from
// System.Windows.Interactivity assembly that is available
// after you have installed Expression Blend.
// (C:\Program Files\Microsoft SDKs\Expression\Blend\Silverlight\v4.0
//  \Libraries\System.Windows.Interactivity.dll)

public class UpdateOnTextChangedBehavior : Behavior<textBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();

        this.AssociatedObject.TextChanged +=
                AssociatedObject_TextChanged;
    }

    void AssociatedObject_TextChanged(
        object sender,
        TextChangedEventArgs e)
    {
        BindingExpression binding =
            this.AssociatedObject.GetBindingExpression(
                TextBox.TextProperty);

        if (binding != null)
        {
            binding.UpdateSource();
        }
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();

        this.AssociatedObject.TextChanged -=
                AssociatedObject_TextChanged;
    }
}

And usage:

<textBox Text="{Binding Title, Mode=TwoWay}">
   <i:Interaction.Behaviors>
      <local:UpdateOnTextChangedBehavior/>
   </i:Interaction.Behaviors>
</textBox>

Tags: ,

Questions?

Consider using our Q&A forum for asking any questions.