Channels ▼
RSS

Tools

What's New In WPF 4.5


Delayed Data Bindings

Why would you establish a timespan after which the source is updated for a data binding in WPF application? The reason is simple: You want to increase UI responsiveness.

You aren't crazy, I am saying Indeed, a delay can increase response time. Just think about a situation in which each change in a control's property value triggers a time-consuming data-binding update. A classic example of this situation is a master-detail binding, in which each change in the master must update the detail. (And the keyboard isn't the only enemy when the user keeps a key pressed that makes continuous changes, a touch-based UI can also have multiple taps in just one second.)

WPF 4.5 introduces a new Delay property that allows you to establish a delay in milliseconds for the data binding to take effect from the target to the source. One example of establishing a value for this new property is when you bind the property that a TextBox changes to another TextBox, and the delay allows you to see blocks of text being inserted in the second TextBox instead of single characters. The data binding triggers the update after the time specified in the delay, and you avoid an update being perfomed for each character that the user modifies.

The new Delay property is also useful when the data binding triggers a time-consuming asynchronous operation. In those cases, you don't want to launch dozens of asynchronous operations to perform unnecessary updates. Instead, you can just establish an appropriate delay and you will minimize the number of asynchronous calls to a minimum. The new Delay property is really useful when you start thinking about all the scenarios in which it might be helpful: You can avoid many undesired UI freezes by just setting a value to this property.

Here's simple example to demonstrate use of the new Delay property. The following lines show the code for a Customer class that defines a Comments property, ready for WPF data binding:

namespace WpfApplication4
{
    using System.ComponentModel;

    /// <summary>
    /// Customer class that provides a Comments property ready for data binding in WPF
    /// </summary>
    public class Customer : INotifyPropertyChanged
    {
        /// <summary>
        /// Invoked when the property value on an element has been changed
        /// </summary>
        /// <param name="propertyName">The property name that changed</param>
        protected virtual void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Comments for the customer
        /// </summary>
        private string _comments;

        /// <summary>
        /// Property Changed event
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
        
        /// <summary>
        /// Gets or sets the comments for the customer
        /// </summary>
        public string Comments
        {
            get
            {
                return _comments;
            }
            set
            {
                _comments = value;
                //// Trigger OnPropertyChanged for this property
                OnPropertyChanged("Comments");
            }
        }
    }
}

The following lines show the XAML code for a WPF 4.5 Window that defines and binds an instance of the previously shown Customer class. The window displays two controls: a TextBox that allows the user to change the value for the Comments property and a TextBlock that is display the Comments text with some effects after the user updates it (see Figure 13).

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication4="clr-namespace:WpfApplication4"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <WpfApplication4:Customer x:Key="Customer" Comments="Enter your comments for this customer" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Customer}">
        <!-- Establish a 1.5 seconds delay for the data binding -->
        <TextBox x:Name="BoundTextBox" Text="{Binding Comments, UpdateSourceTrigger=PropertyChanged, Delay=1500}" Margin="8,10,11.4,285.8"/>
        <!-- The following TextBlock is binded to the Comments property that the TextBox allows the user to change -->
        <TextBlock Text="{Binding Comments}" Width="500" Margin="10,74,8.4,144.8" FontSize="24" FontFamily="Britannic Bold" RenderTransformOrigin="0.5,0.5" >
            <TextBlock.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform AngleX="-36" AngleY="2"/>
                    <RotateTransform/>
                    <TranslateTransform/>
                </TransformGroup>
            </TextBlock.RenderTransform>
        </TextBlock>
    </Grid>
</Window>


Figure 13: The XAML preview displaying the TextBox and the TextBlock with the initial text for the Customer.Comments property.

The binding established for the TextBox sets a delay of 1500 milliseconds:

  <TextBox x:Name="BoundTextBox" Text="{Binding Comments, UpdateSourceTrigger=PropertyChanged, Delay=1500}" Margin="8,10,11.4,285.8"/>

This way, the binding update will be triggered with the specified delay. It is easier to understand the effect by executing the application and changing the text. The TextBlock with the effects won't reflect changes when you start changing the contents for the TextBox (see Figure 14). After 1.5 seconds, the data binding makes effect and the TextBlock is updated (see Figure 15).


Figure 14: The TextBlock has a different text than the TextBox, that changes after 1.5 seconds.


Figure 15: After the specified delay, the TextBlock is updated.

Conclusion

WPF 4.5 provides many performance improvements that you will notice as soon as you start working with it. There are important changes for the VirtualizingPanel when you work with huge amounts of data, as well as enhanced support for both synchronous and asynchronous validations with the INotifyDataErrorInfo interface (inherited from Silverlight), and the data bindings to custom types. In addition, the ability to access and modify collections on different threads than the one that created the collection makes it possible to provide a more responsive UI.

In this article, I've provided a few examples of some of the most useful features I found in WPF 4.5, which should help you to create more responsive applications and improve overall user experience.


Gaston Hillar is a long-time Windows programmer and a frequent contributor to Dr. Dobb's.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video