Keylight上的Silverlight双向数据绑定

时间:2010-03-16 13:40:07

标签: silverlight

当Silverlight中的key up事件触发时,是否有办法触发双向数据绑定。目前,我不得不关注文本框以使绑定解雇。

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

3 个答案:

答案 0 :(得分:2)

您还可以使用Blend交互行为来创建可重用行为,以更新KeyUp上的绑定,例如:

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

答案 1 :(得分:1)

我通过这样做实现了这个目标......

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

和XAML

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

答案 2 :(得分:0)

我们对我们的应用程序有相同的要求,但有些客户使用的是MacO。 MacO并不总是触发keyup事件(至少在Firefox中)。

在接受的答案中,由于UpdateSourceTrigger设置为Explicit,这会成为一个大问题,但事件永远不会触发。结果:你永远不会更新绑定。

但是,TextChanged事件始终在触发。听取这一个,一切都很好:)

这是我的版本:

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

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

UpdateBinding ExtensionMethod:

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