Silverlight Two-way Keyword Binding

Is there a way to trigger two-way data binding when the key up event fires in Silverlight. Currently, I have to lose focus on the text box to get attached to the fire.

<TextBox x:Name="Filter" KeyUp="Filter_KeyUp" Text="{Binding Path=Filter, Mode=TwoWay }"/>
+3
source share
3 answers

I achieved this by doing this ...

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

and in xaml

<TextBox x:Name="Filter"  Text="{Binding Path=Filter, Mode=TwoWay, UpdateSourceTrigger=Explicit}" KeyUp="Filter_KeyUp"/>
+1
source

You can also use the Blend interactivity behavior to create reusable behavior that updates the binding to KeyUp, for example:

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;
    }
}
+2
source

, MacOs. MacOs keyup ( , Firefox).

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

However, the TextChanged event always fires. listen to this and all is well :)

Here is my version:

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

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

And UpdateBinding ExtensionMethod:

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

Source: https://habr.com/ru/post/1737149/


All Articles