Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Text Box with Delayed Binding

0.00/5 (No votes)
6 Oct 2009 1  
A TextBox that waits a user defined interval of time after the user has stopped typing to update its binding source

Introduction

Today I found myself writing a Search interface, I was searching a large amount of data and wanted the user to just be able to type their search query and not have to hit a button to execute the search. At first I tried using a straight WPF textBox with UpdateSourceTrigger set to PropertyChanged, however this was executing the search functionality on each keystroke, which was too slow. What I wanted was for the search to be executed when the user finished typing.

Solution

I have derived a subclass of TextBox which has a property DelayTime. As the user enters a keystroke a timer is started, if the timer reaches the DelayTime before another keystroke (set in milliseconds) the DataBinding source is updated. In the application, I am working on allowing users to type away and when they stop typing, the search is executed. I have included a few other little features; the binding will update if the text box loses focus and also when the enter or return key is pressed.

Using the Code 

The included project shows how to use the DelayedBindingTextBox, which is basically the same as using a TextBox, except you can set a DelayTime (in milliseconds).

<local:DelayedBindingTextBox
            DelayTime="500"
            Text="{Binding Path=MyTextProperty}" />

If the Text property has its binding set to UpdateSourceTrigger=PropertyChanged, the behaviour will not be any different from a standard TextBox.

In the (very ugly - I'm not a designer) screenshot below, you can see that although the text in the textbox has changed to "original text has changed", the text below (which represents what the text box is bound to) is still "original text", as the timer has not reached 3886 ms. As soon as it does, the text below the box will be updated.

screenshot.png

Points of Interest

The override of the OnTextChanged method in the DelayedbindingTextBox is worth a mention, just to have a look at the anonymous method with an enclosed call to a delegate method. Anonymous methods are so powerful, and can be just as confusing as any code I have ever read.

History

  • 01/10/09: Initial posting
  • 05/10/09: Made changes to deal with the situation when the textbox is unloaded or the binding information changes before the update is made. As this control uses threading, there exists the possibility that the binding can become invalid before the timer expires.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here