Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Binding Textbox to ViewModel

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.

like image 925
Sonic Soul Avatar asked Mar 17 '11 14:03

Sonic Soul


2 Answers

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

like image 137
Maverik Avatar answered Sep 21 '22 13:09

Maverik


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.

like image 43
Jarek Avatar answered Sep 25 '22 13:09

Jarek