James Hughes
James Hughes

Reputation: 6194

Silverlight Two Way Data Binding on Key Up

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 }"/>

Upvotes: 3

Views: 2096

Answers (3)

St&#233;phane
St&#233;phane

Reputation: 11864

We had the same requirement on our app, but some clients are on MacOs. MacOs does not always fire the keyup event (at least in Firefox).

In the accepted answer, this becomes a big problem since the UpdateSourceTrigger is set to Explicit, but the event never fires. Consequence : you never update the binding.

However, the TextChanged event is always firing. listen to this one instead and all is good :)

Here is my version :

public class AutoUpdateTextBox : TextBox
{
    public AutoUpdateTextBox()
    {
        TextChanged += OnTextChanged;
    }

    private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        this.UpdateBinding(TextProperty);
    }
}

And the UpdateBinding ExtensionMethod :

    public static void UpdateBinding(this FrameworkElement element, 
                                     DependencyProperty dependencyProperty)
    {
        var bindingExpression = element.GetBindingExpression(dependencyProperty);
        if (bindingExpression != null)
            bindingExpression.UpdateSource();
    } 

Upvotes: 0

Graeme Bradbury
Graeme Bradbury

Reputation: 3721

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;
    }
}

Upvotes: 2

James Hughes
James Hughes

Reputation: 6194

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"/>

Upvotes: 1

Related Questions