开发者

Silverlight Two Way Data Binding on Key Up

Is there a way to fire a two w开发者_如何学Pythonay 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 }"/>


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


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


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();
    } 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜