【问题标题】:Silverlight Two Way Data Binding on Key UpSilverlight 键上的双向数据绑定
【发布时间】:2010-03-16 13:40:06
【问题描述】:

有没有办法在 Silverlight 中触发按键事件时触发双向数据绑定。目前我必须失去对文本框的关注才能触发绑定。

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

【问题讨论】:

    标签: silverlight


    【解决方案1】:

    您还可以使用 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;
        }
    }
    

    【讨论】:

    • 如果您要包含 OPs Xaml 的外观以利用此行为,则此答案会更完整。
    【解决方案2】:

    我通过这样做实现了这一点......

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

    在 XAML 中

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

    【讨论】:

    • 哦,您使用的是 SL4。很好,因为 SL3 中没有 BindingExpression
    【解决方案3】:

    我们对我们的应用程序有相同的要求,但有些客户使用的是 MacO。 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 ExtensionMethod:

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

    【讨论】:

      猜你喜欢
      • 2011-10-29
      • 1970-01-01
      • 1970-01-01
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-24
      • 2015-08-08
      相关资源
      最近更新 更多