绑定绑定的Delay属性

时间:2017-05-03 15:07:07

标签: wpf data-binding

我正在尝试动态更改绑定的延迟:

<TextBox Text="{Binding Text, Delay={Binding BindingDelay}}">
</TextBox>

但我收到错误:

  

A&#39;绑定&#39;无法设置延迟&#39;属性类型&#39;绑定&#39;一个   &#39;结合&#39;只能在a的DependencyProperty上设置   的DependencyObject。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

使用后无法更改Binding。您可以创建新的Binding并应用它。

现在,要将binding应用于non-DP,您可以使用AttachedProperty,并在其PropertyChangedHandler中执行您喜欢的操作。

我测试了这个概念如下,发现它有效:

// Using a DependencyProperty as the backing store for BoundedDelayProp.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty BoundedDelayPropProperty =
        DependencyProperty.RegisterAttached("BoundedDelayProp", typeof(int), typeof(Window5), new PropertyMetadata(0, OnBoundedDelayProp_Changed));

    private static void OnBoundedDelayProp_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        TextBox tb = d as TextBox;
        Binding b = BindingOperations.GetBinding(tb, TextBox.TextProperty);

        BindingOperations.ClearBinding(tb, TextBox.TextProperty);

        Binding newbinding = new Binding();
        newbinding.Path = b.Path;
        newbinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
        newbinding.Delay = (int)e.NewValue;

        BindingOperations.SetBinding(tb, TextBox.TextProperty, newbinding);
    }

XAML:

<TextBox local:MyWindow.BoundedDelayProp="{Binding DelayTime}"
         Text="{Binding Time, UpdateSourceTrigger=PropertyChanged, Delay=5000}" />

Delay时间会相应变化。

看看这是否能解决您的问题。