代码之家  ›  专栏  ›  技术社区  ›  James Hughes

向上键上的Silverlight双向数据绑定

  •  3
  • James Hughes  · 技术社区  · 15 年前

    当silverlight中的key up事件触发时,是否有方法触发双向数据绑定。目前,我不得不失去对文本框的关注,使绑定着火。

    <TextBox x:Name="Filter" KeyUp="Filter_KeyUp" Text="{Binding Path=Filter, Mode=TwoWay }"/>
    
    3 回复  |  直到 13 年前
        1
  •  2
  •   Graeme Bradbury    15 年前

    您还可以使用混合交互性行为来创建可重用的行为,以更新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;
        }
    }
    
        2
  •  1
  •   James Hughes    15 年前

    我通过这样做达到了这个目的…

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

    在xaml中

    <TextBox x:Name="Filter"  Text="{Binding Path=Filter, Mode=TwoWay, UpdateSourceTrigger=Explicit}" KeyUp="Filter_KeyUp"/>
    
        3
  •  0
  •   Stéphane    13 年前

    我们对我们的应用程序也有同样的要求,但有些客户端在macos上。 macos并不总是触发keyup事件(至少在firefox中)。

    在公认的答案中,这成为一个大问题,因为updatesourcetrigger被设置为explicit,但事件从不触发。结果:您永远不会更新绑定。

    但是,textchanged事件始终在触发。听这首歌,一切都很好:)

    这是我的版本:

    public class AutoUpdateTextBox : TextBox
    {
        public AutoUpdateTextBox()
        {
            TextChanged += OnTextChanged;
        }
    
        private void OnTextChanged(object sender, TextChangedEventArgs e)
        {
            this.UpdateBinding(TextProperty);
        }
    }
    

    以及updateBinding扩展方法:

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