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.
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.
Is this programmer guy you know...
He writes in C#, WPF and does some audio bits and pieces for the iPhone.
He is into electronic music, and loves a good drum machine in the morning and a synthesizer before bed.
Is using twitter - @aranmul
He has a site for some test projects for using Core Audio on the iPhone
here
He is compiling a collection of books he has found useful/interesting
here