26
votes

I have a textbox that is bound to a property on my ViewModel called DatabaseFilter

here is the implementation of the property

public string DatabaseFilter {
    get { return _databaseFilter; }
    set { 
        _databaseFilter = value;
        FilterDatabases();
    }
}

as you can see, i am trying to trigger a filtering based on what is typed into the textbox.

The problem is, that the setter is triggered when the textbox loses focus. So typing into the textbox is not doing anything, until the user presses TAB.

Is it possible to make the binding update underling viewmodel with each key press via binding? I would like to avoid having to add key down/up events, to keep the UI/codebehind as clean as possible.

6

6 Answers

44
votes

Set UpdateSourceTrigger on your TextBox to PropertyChanged (which defaults to LostFocus)

25
votes

You need to set UpdateSourceTrigger=PropertyChanged property on your binding expression, e.g.

<TextBox Text="{Binding Path=DatabaseFilter, UpdateSourceTrigger=PropertyChanged}" />

There are also different values available, like: Explicit - when you need to explicitly call update on binding; LostFocus - this is default for TextBox, updates binding after control looses focus.

You need to remember, that if your filtering action is executed on UI thread, filtering after each keystroke may not be wisest thing to do, since user experience may be seriously affected by delays created by this filtering. If you are positive, that you need to filter after each keystroke, be sure that filtering will be quick (e.g. there is only few items to filter), or that you will filter in background thread.

5
votes

Change your binding to update the source whenever the property changes:

<TextBox Text="{Binding DatabaseFilter, UpdateSourceTrigger=PropertyChanged}">

3
votes

UpdateSourceTrigger=PropertyChanged should solve this issue for you

3
votes

Use the Binding.UpdateSourceTrigger property on your binding. The default update source trigger is focus loss. You can change it so that every time the text in the textbox changes the binding will happen.

see http://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx

0
votes

Create a command in your VM "FilterDatabaseCommand", the bind the event "TextChanged" of the textbox to this command (use the EventToCommand behavior).

Or simply change your code to this :

public string DatabaseFilter {
    get { return _databaseFilter; }
    set { 
        if(_databaseFilter != value) {
            _databaseFilter = value;
            FilterDatabases();
        }
    }
}