paul
paul

Reputation: 13516

How to bind to application settings and be able to write unit tests when using the MVVM pattern?

I am trying to get started with the MVVM pattern and am struggling with this problem.

I have an input field where I enter the value for a search filter. I want to remember the value so, normally, I would save it in the application settings.

The input field is 2way bound to the settings in the View which works ok and doesn't create any application-dependencies in the ViewModel. This is important for unit testing, I think.

Now I would like to respond to changes in the input field and apply the filter but the binding is with the application settings and not the ViewModel.

How can I solve this problem? Can I 'double bind' a field - to the settings AND to the ViewModel? What is a sensible and pragmatic approach to this situation?

Upvotes: 1

Views: 180

Answers (1)

slugster
slugster

Reputation: 49974

There are a couple of simple ways to deal with this, depending on your exact setup.

If you have just a textbox that the user types into and you filter the data in an interactive way, then you can use a TextChanged event handler in the code behind of the view*. From that event handler you can then invoke a command exposed by the viewmodel, that command can take the search text as its input and filter the data accordingly. Of course the viewmodel can also acceess your application settings data object, but I prefer the more immediate and declarative approach of having it as a parameter to the command.

If you have the textbox and then the search/filter is kicked off via a button, then you can just expose a command from the viewmodel which the button binds to, and as the command parameter you can use element binding to pass the text through to the command.

Using either of these methods your search/filter code in the viewmodel is very testable. You typically don't unit test code in the UI, so you don't need to worry about the code in the TextChanged handler. I should also mention that if you are using the interactive search then Reactive Extensions could be quite useful for you as they provide a convenient way to throttle the calls to the viewmodel.

*some people who consider themselves absolute purists would shudder at the thought of code in the view, but it's okay to do that provided it is purely UI/display related code, you can then call into the viewmodel via it's interface.

Upvotes: 1

Related Questions