During my WPF presentation for the NYC .NET Developer Group a few days ago, someone in the audience asked a question about the data binding system which piqued my interest. He asked if it is possible to control how frequently a binding target is updated.
Suppose that you have a data source where a property’s value changes very rapidly, perhaps several dozen times per second. You would not want the UI to display all of those values because it would just look like a blur. It would be better to govern how often the binding source’s new values are pushed to the binding target. The question is, how can you do that in WPF?
One solution is to create a value converter which governs the data flow between source and target. The converter can keep a time stamp which it uses to determine when the new source values can be pushed to the target. Every time the data is pushed, the time stamp is updated so that the next push will not occur until a pre-defined duration has elapsed.
I put together a demo app which shows how to do this. In the demo, the rapidly changing data source is called RandomNumberEngine. It has a public property named Current, which returns a random number. That random number changes once every millisecond. When the value changes, the PropertyChanged event is raised so that the binding system will attempt to push that new value into a TextBlock in the UI. The TextBlock’s Text property is bound to the Current property on the RandomNumberEngine, and that binding is where we use the UpdateThresholdConverter to govern how often the data is pushed.
Here is the XAML for the demo app’s main Window contents:
Here is the entire UpdateThresholdConverter class:
The UpdateThreshold property represents the number of milliseconds which must elapse between successful attempts to push a new value from the binding source to target. Returning Binding.DoNothing from the Convert method informs the binding system that no values should be updated, leaving the attempt to transfer data as a no-op.
Download the demo project here: Update Threshold Converter (demo project) Be sure to change the file extension from .DOC to .ZIP and then decompress it.