Immediate data binding update

While writing a WPF application that made use of incremental search basing on the value of a TextBox I've faced a problem that the ViewModel (the DataContext) was notified about the changed value of the property only when it lost focus.

So let's say I had on the ViewModel side:

 

public string QueryString
{
    get
    {
        return _queryString;
    }
    set
    {
        _queryString = value;
        OnPropertyChanged("Patients");
    }
}

and in my WPF:

 

<TextBox Height="36" Margin="12,23,12,0" VerticalAlignment="Top" FontSize="18" Text="{Binding QueryString, Mode=TwoWay}" />

A change on the QueryString property on the ViewModel should be whenever the value of the TextBox is changed - no matter whether it lost focus or not.

The solution to this is to set the UpdateSourceTrigger property of the binding to "PropertyChanged". Now a PropertyChanged is triggered immediately after a new character is typed (or pasted):

 

<TextBox Height="36" Margin="12,23,12,0" VerticalAlignment="Top" FontSize="18" Text="{Binding QueryString, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

 

Yet, everytime a new value is entered a new search is performed. Although the searching algorithm is quite efficient (as it's built on suffix trees) but the user could experience some delays between his keystroke and the new value appearing on his TextBox, thus why I recommend setting it's IsAsync value to "true":

 

<TextBox Height="36" Margin="12,23,12,0" VerticalAlignment="Top" FontSize="18" Text="{Binding QueryString, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, IsAsync=True}" />
©2008 Karim Agha. All rights reserved.