tags:

views:

208

answers:

2

Is there a way to fire a two way data bind when the key up event fires in Silverlight. Currently I have to lose focus on the textbox to get the binding to fire.

<TextBox x:Name="Filter" KeyUp="Filter_KeyUp" Text="{Binding Path=Filter, Mode=TwoWay }"/>
A: 

I have achieved this by doing this...

Filter.GetBindingExpression(TextBox.TextProperty).UpdateSource();

and in the XAML

<TextBox x:Name="Filter"  Text="{Binding Path=Filter, Mode=TwoWay, UpdateSourceTrigger=Explicit}" KeyUp="Filter_KeyUp"/>
kouPhax
Oh, you're using SL4. Good, because BindingExpression was not there in SL3
Timores
BindingExpression was in SL3
Graeme Bradbury
+1  A: 

You could also use Blend interactivity behaviours to create a reusable behaviour that updates the binding on KeyUp eg:

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

        AssociatedObject.KeyUp += AssociatedObject_KeyUp;

    }

    void AssociatedObject_KeyUp(object sender, KeyEventArgs e)
    {
        var bindingExpression = AssociatedObject.GetBindingExpression(TextBox.TextProperty);

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

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

        AssociatedObject.KeyUp -= AssociatedObject_KeyUp;
    }
}
Graeme Bradbury
This answer would be more complete if you were to include what the OPs Xaml should look like to take advantage of this behavior.
AnthonyWJones