Raising a PropertyChanged event during a Pause in TextBox entry?
Asked Answered
T

5

5

I was wondering if it's possible to raise a PropertyChanged event when the user pauses while typing text into a TextBox? Or more specifically, I want to run a method X seconds after the user stops typing in a TextBox.

For example, I have a form with a TextBox and nothing else. The user types in a 1-9 digit Id value into the TextBox, a fairly resource-intensive background process loads the record.

I do not want to use the UpdateSouceTrigger=PropertyChanged because that would cause the resource-intensive background process to run whenever a character gets typed, so a 9-digit ID number starts off 9 of these processes.

I also don't want to use UpdateSourceTrigger=LostFocus because there is nothing else on the form to make the TextBox lose focus.

So is there a way to cause my background process to run only after the user pauses when typing in the Id number?

Tram answered 15/7, 2011 at 17:57 Comment(1)
Here is one example of using a custom TextBox/Timer.Drysalt
G
8

Prepare for code-dump.

I've done this with a WPF Fake Behavior (an attached DP that acts like a behavior). This code works, but it isn't pretty and it may result in leaks. Probably need to replace all the references with weak references, etc.

Here's the Behavior class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Data;
using System.ComponentModel;

namespace BehaviorForDelayedTrigger
{
    public static class DelayedUpdateBehavior
    {
        #region TargetProperty Attached DependencyProperty
        /// <summary>
        /// An Attached <see cref="DependencyProperty"/> of type <see cref="DependencyProperty"/> defined on <see cref="DependencyObject">DependencyObject instances</see>.
        /// </summary>
        public static readonly DependencyProperty TargetPropertyProperty = DependencyProperty.RegisterAttached(
          TargetPropertyPropertyName,
          typeof(DependencyProperty),
          typeof(DelayedUpdateBehavior),
          new FrameworkPropertyMetadata(null, OnTargetPropertyChanged)
        );

        /// <summary>
        /// The name of the <see cref="TargetPropertyProperty"/> Attached <see cref="DependencyProperty"/>.
        /// </summary>
        public const string TargetPropertyPropertyName = "TargetProperty";

        /// <summary>
        /// Sets the value of the <see cref="TargetPropertyProperty"/> on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        public static void SetTargetProperty(DependencyObject element, DependencyProperty value)
        {
            element.SetValue(TargetPropertyProperty, value);
        }

        /// <summary>
        /// Gets the value of the <see cref="TargetPropertyProperty"/> as set on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        /// <returns><see cref="DependencyProperty"/></returns>
        public static DependencyProperty GetTargetProperty(DependencyObject element)
        {
            return (DependencyProperty)element.GetValue(TargetPropertyProperty);
        }

        /// <summary>
        /// Called when <see cref="TargetPropertyProperty"/> changes
        /// </summary>
        /// <param name="d">The <see cref="DependencyObject">event source</see>.</param>
        /// <param name="e"><see cref="DependencyPropertyChangedEventArgs">event arguments</see></param>
        private static void OnTargetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var prop = e.NewValue as DependencyProperty;
            if(prop == null)
                return;
            d.Dispatcher.BeginInvoke(
                (Action<DependencyObject, DependencyProperty>)
                    ((target, p) => new PropertyChangeTimer(target, p)), 
                DispatcherPriority.ApplicationIdle, 
                d, 
                prop);

        }
        #endregion
        #region Milliseconds Attached DependencyProperty
        /// <summary>
        /// An Attached <see cref="DependencyProperty"/> of type <see cref="int"/> defined on <see cref="DependencyObject">DependencyObject instances</see>.
        /// </summary>
        public static readonly DependencyProperty MillisecondsProperty = DependencyProperty.RegisterAttached(
          MillisecondsPropertyName,
          typeof(int),
          typeof(DelayedUpdateBehavior),
          new FrameworkPropertyMetadata(1000)
        );

        /// <summary>
        /// The name of the <see cref="MillisecondsProperty"/> Attached <see cref="DependencyProperty"/>.
        /// </summary>
        public const string MillisecondsPropertyName = "Milliseconds";

        /// <summary>
        /// Sets the value of the <see cref="MillisecondsProperty"/> on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        public static void SetMilliseconds(DependencyObject element, int value)
        {
            element.SetValue(MillisecondsProperty, value);
        }

        /// <summary>
        /// Gets the value of the <see cref="MillisecondsProperty"/> as set on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        /// <returns><see cref="int"/></returns>
        public static int GetMilliseconds(DependencyObject element)
        {
            return (int)element.GetValue(MillisecondsProperty);
        }
        #endregion
        private class PropertyChangeTimer
        {
            private DispatcherTimer _timer;
            private BindingExpression _expression;
            public PropertyChangeTimer(DependencyObject target, DependencyProperty property)
            {
                if (target == null)
                    throw new ArgumentNullException("target");
                if (property == null)
                    throw new ArgumentNullException("property");
                if (!BindingOperations.IsDataBound(target, property))
                    return;
                _expression = BindingOperations.GetBindingExpression(target, property);
                if (_expression == null)
                    throw new InvalidOperationException("No binding was found on property "+ property.Name + " on object " + target.GetType().FullName);
                DependencyPropertyDescriptor.FromProperty(property, target.GetType()).AddValueChanged(target, OnPropertyChanged);
            }

            private void OnPropertyChanged(object sender, EventArgs e)
            {
                if (_timer == null)
                {
                    _timer = new DispatcherTimer();
                    int ms = DelayedUpdateBehavior.GetMilliseconds(sender as DependencyObject);
                    _timer.Interval = TimeSpan.FromMilliseconds(ms);
                    _timer.Tick += OnTimerTick;
                    _timer.Start();
                    return;
                }
                _timer.Stop();
                _timer.Start();
            }

            private void OnTimerTick(object sender, EventArgs e)
            {
                _expression.UpdateSource();
                _expression.UpdateTarget();
                _timer.Stop();
                _timer = null;
            }
        }
    }
}

And here's an example of how it is used:

<Window
    x:Class="BehaviorForDelayedTrigger.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:t="clr-namespace:BehaviorForDelayedTrigger">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition
                Height="auto" />
        </Grid.RowDefinitions>
        <Viewbox>
            <TextBlock
                x:Name="TargetTextBlock"
                Background="Red" />
        </Viewbox>
        <TextBox
            t:DelayedUpdateBehavior.TargetProperty="{x:Static TextBox.TextProperty}"
            t:DelayedUpdateBehavior.Milliseconds="1000"
            Grid.Row="1"
            Text="{Binding Text, ElementName=TargetTextBlock, UpdateSourceTrigger=Explicit}" />
    </Grid>
</Window>

The gist of this is...

You set the attached property on the bound UIElement, passing in the DP you wish to delay. At this point, I have the target of the attached property and the property to be delayed, so I can set things up. I do have to wait until the binding is available, so I have to use the Dispatcher to instantiate my watcher class after databinding has been set up. Fail to do this and you can't grab the binding expression.

The watcher class grabs the binding and adds an update listener to the DependencyProperty. In the listener, I set up a timer (if we haven't updated) or reset the timer. Once the Timer ticks, I fire off the binding expression.

Again, it works, but it definitely needs cleanup. Also, you can just use the DP via its name with the following code snippet:

FieldInfo fieldInfo = instance.GetType()
                             .GetField(name, 
                                 BindingFlags.Public | 
                                 BindingFlags.Static | 
                                 BindingFlags.FlattenHierarchy);
return (fieldInfo != null) ? (DependencyProperty)fieldInfo.GetValue(null) : null;

You might have to tack "Property" onto name, but that's easy compared to using x:Static.

Gearwheel answered 15/7, 2011 at 19:6 Comment(2)
@Will That's an interesting way to write a Behavior such that the Xaml user can pass in multiple pieces of related data. Your use of the nested class seems to be the key to making that work using only Attached Props. I am curious to know if you had considered writing a Blend behavior instead, and if so, what made you choose this approach? I have wrestled with these decisions as well (I've written about this here), and I usually find it easier to write Blend behaviors for these multiple-param cases, but there are times when I prefer AP's instead.Pun
@jason I'm a bit prejudiced against blend behaviors because they're not part of the BCL. Also am unclear how you get the assembly in the first place without installing blend itself. In other words, it just smells.Gearwheel
T
10

Set UpdateSourceTrigger=PropertyChanged, and then each time the property changes, kick off a timer for the delay you'd like. If the property is changed again prior to the timer tick, then cancel the old timer and kick off a new one. If the timer does tick, then you know the property hasn't changed in X seconds, and you can kick off the background process.

Tippets answered 15/7, 2011 at 18:1 Comment(5)
@Tram Mine was the first answer (right now it was posted 39 minutes ago as opposed to 38 for the other) but as long as you got the problem solved, that's what SO is for :)Tippets
You all are lame. It takes a real man to use attached DependencyProperties to create reusable behaviors which... eh, whatevs.Gearwheel
@Will, your implementation is good in that it takes full advantage of the framework, however, if not used carefully it can be dangerous. If I'm reading your code right, the property change event will not be fired until the delay is satisfied. I personally like dlev's solution because some handlers may not want a delay in the event.Preternatural
@Jay: Not sure what you're talking about. You apply the behavior on any DependencyObject that you wish to delay a binding update on. You can configure the delay as well. That's the requirements. There might be some issues with referenced instances hanging about, but I'm not 100% sure about that (I created the behavior as a learning experience, never took it past the prototype stage).Gearwheel
Let me give you an example: I have two handlers I need to wire to this event. 1) A kicker for a background process that should be on a delay (your all set here). 2) A validator that needs to prevent more than 1 number being entered in (if u delay this event, then the user could have as many as they want as long as they enter quickly). What I mean is the handler needs to provide the delay, not the property firing the event.Preternatural
G
8

Prepare for code-dump.

I've done this with a WPF Fake Behavior (an attached DP that acts like a behavior). This code works, but it isn't pretty and it may result in leaks. Probably need to replace all the references with weak references, etc.

Here's the Behavior class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Data;
using System.ComponentModel;

namespace BehaviorForDelayedTrigger
{
    public static class DelayedUpdateBehavior
    {
        #region TargetProperty Attached DependencyProperty
        /// <summary>
        /// An Attached <see cref="DependencyProperty"/> of type <see cref="DependencyProperty"/> defined on <see cref="DependencyObject">DependencyObject instances</see>.
        /// </summary>
        public static readonly DependencyProperty TargetPropertyProperty = DependencyProperty.RegisterAttached(
          TargetPropertyPropertyName,
          typeof(DependencyProperty),
          typeof(DelayedUpdateBehavior),
          new FrameworkPropertyMetadata(null, OnTargetPropertyChanged)
        );

        /// <summary>
        /// The name of the <see cref="TargetPropertyProperty"/> Attached <see cref="DependencyProperty"/>.
        /// </summary>
        public const string TargetPropertyPropertyName = "TargetProperty";

        /// <summary>
        /// Sets the value of the <see cref="TargetPropertyProperty"/> on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        public static void SetTargetProperty(DependencyObject element, DependencyProperty value)
        {
            element.SetValue(TargetPropertyProperty, value);
        }

        /// <summary>
        /// Gets the value of the <see cref="TargetPropertyProperty"/> as set on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        /// <returns><see cref="DependencyProperty"/></returns>
        public static DependencyProperty GetTargetProperty(DependencyObject element)
        {
            return (DependencyProperty)element.GetValue(TargetPropertyProperty);
        }

        /// <summary>
        /// Called when <see cref="TargetPropertyProperty"/> changes
        /// </summary>
        /// <param name="d">The <see cref="DependencyObject">event source</see>.</param>
        /// <param name="e"><see cref="DependencyPropertyChangedEventArgs">event arguments</see></param>
        private static void OnTargetPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var prop = e.NewValue as DependencyProperty;
            if(prop == null)
                return;
            d.Dispatcher.BeginInvoke(
                (Action<DependencyObject, DependencyProperty>)
                    ((target, p) => new PropertyChangeTimer(target, p)), 
                DispatcherPriority.ApplicationIdle, 
                d, 
                prop);

        }
        #endregion
        #region Milliseconds Attached DependencyProperty
        /// <summary>
        /// An Attached <see cref="DependencyProperty"/> of type <see cref="int"/> defined on <see cref="DependencyObject">DependencyObject instances</see>.
        /// </summary>
        public static readonly DependencyProperty MillisecondsProperty = DependencyProperty.RegisterAttached(
          MillisecondsPropertyName,
          typeof(int),
          typeof(DelayedUpdateBehavior),
          new FrameworkPropertyMetadata(1000)
        );

        /// <summary>
        /// The name of the <see cref="MillisecondsProperty"/> Attached <see cref="DependencyProperty"/>.
        /// </summary>
        public const string MillisecondsPropertyName = "Milliseconds";

        /// <summary>
        /// Sets the value of the <see cref="MillisecondsProperty"/> on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        public static void SetMilliseconds(DependencyObject element, int value)
        {
            element.SetValue(MillisecondsProperty, value);
        }

        /// <summary>
        /// Gets the value of the <see cref="MillisecondsProperty"/> as set on the given <paramref name="element"/>.
        /// </summary>
        /// <param name="element">The <see cref="DependencyObject">target element</see>.</param>
        /// <returns><see cref="int"/></returns>
        public static int GetMilliseconds(DependencyObject element)
        {
            return (int)element.GetValue(MillisecondsProperty);
        }
        #endregion
        private class PropertyChangeTimer
        {
            private DispatcherTimer _timer;
            private BindingExpression _expression;
            public PropertyChangeTimer(DependencyObject target, DependencyProperty property)
            {
                if (target == null)
                    throw new ArgumentNullException("target");
                if (property == null)
                    throw new ArgumentNullException("property");
                if (!BindingOperations.IsDataBound(target, property))
                    return;
                _expression = BindingOperations.GetBindingExpression(target, property);
                if (_expression == null)
                    throw new InvalidOperationException("No binding was found on property "+ property.Name + " on object " + target.GetType().FullName);
                DependencyPropertyDescriptor.FromProperty(property, target.GetType()).AddValueChanged(target, OnPropertyChanged);
            }

            private void OnPropertyChanged(object sender, EventArgs e)
            {
                if (_timer == null)
                {
                    _timer = new DispatcherTimer();
                    int ms = DelayedUpdateBehavior.GetMilliseconds(sender as DependencyObject);
                    _timer.Interval = TimeSpan.FromMilliseconds(ms);
                    _timer.Tick += OnTimerTick;
                    _timer.Start();
                    return;
                }
                _timer.Stop();
                _timer.Start();
            }

            private void OnTimerTick(object sender, EventArgs e)
            {
                _expression.UpdateSource();
                _expression.UpdateTarget();
                _timer.Stop();
                _timer = null;
            }
        }
    }
}

And here's an example of how it is used:

<Window
    x:Class="BehaviorForDelayedTrigger.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:t="clr-namespace:BehaviorForDelayedTrigger">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition
                Height="auto" />
        </Grid.RowDefinitions>
        <Viewbox>
            <TextBlock
                x:Name="TargetTextBlock"
                Background="Red" />
        </Viewbox>
        <TextBox
            t:DelayedUpdateBehavior.TargetProperty="{x:Static TextBox.TextProperty}"
            t:DelayedUpdateBehavior.Milliseconds="1000"
            Grid.Row="1"
            Text="{Binding Text, ElementName=TargetTextBlock, UpdateSourceTrigger=Explicit}" />
    </Grid>
</Window>

The gist of this is...

You set the attached property on the bound UIElement, passing in the DP you wish to delay. At this point, I have the target of the attached property and the property to be delayed, so I can set things up. I do have to wait until the binding is available, so I have to use the Dispatcher to instantiate my watcher class after databinding has been set up. Fail to do this and you can't grab the binding expression.

The watcher class grabs the binding and adds an update listener to the DependencyProperty. In the listener, I set up a timer (if we haven't updated) or reset the timer. Once the Timer ticks, I fire off the binding expression.

Again, it works, but it definitely needs cleanup. Also, you can just use the DP via its name with the following code snippet:

FieldInfo fieldInfo = instance.GetType()
                             .GetField(name, 
                                 BindingFlags.Public | 
                                 BindingFlags.Static | 
                                 BindingFlags.FlattenHierarchy);
return (fieldInfo != null) ? (DependencyProperty)fieldInfo.GetValue(null) : null;

You might have to tack "Property" onto name, but that's easy compared to using x:Static.

Gearwheel answered 15/7, 2011 at 19:6 Comment(2)
@Will That's an interesting way to write a Behavior such that the Xaml user can pass in multiple pieces of related data. Your use of the nested class seems to be the key to making that work using only Attached Props. I am curious to know if you had considered writing a Blend behavior instead, and if so, what made you choose this approach? I have wrestled with these decisions as well (I've written about this here), and I usually find it easier to write Blend behaviors for these multiple-param cases, but there are times when I prefer AP's instead.Pun
@jason I'm a bit prejudiced against blend behaviors because they're not part of the BCL. Also am unclear how you get the assembly in the first place without installing blend itself. In other words, it just smells.Gearwheel
C
5

If you are using .NET 4.5 or above you can use the Delay property of a Binding. It's really easy:

<TextBox Text="{Binding Name, Delay=500, UpdateSourceTrigger=PropertyChanged}"/>
Cinquain answered 16/4, 2018 at 15:34 Comment(0)
M
4

I think this is exactly what you're looking for: DelayBinding for WPF

It is custom binding that does exactly what the two answers above suggest. It maxes it as easy as writing <TextBox Text="{z:DelayBinding Path=SearchText}" /> or to specify the delay interval <TextBox Text="{z:DelayBinding Path=SearchText, Delay='00:00:03'}" />

Maitund answered 15/7, 2011 at 19:0 Comment(0)
P
2

Why not use UpdateSouceTrigger=PropertyChanged, but instead of directly firing off your background process have it reset a timer that will fire off that process after, say, 3 seconds. That way if they type something else in before 3 seconds is up, the timer gets reset and the background process will occur +3 more seconds from now.

Preternatural answered 15/7, 2011 at 18:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.