user2381422
user2381422

Reputation: 5805

Should I always use Command even though it might not be necessary?

Should I always use Command even though it might not be necessary?

Or should I only use Command in the case where more things, menu items, buttons, whatever, when clicked execute the same code?

Maybe it is good practice to always use Command, or maybe it adds additional unnecessary complexity. I am new to WPF so please share some advices.

Upvotes: 1

Views: 306

Answers (1)

Marc
Marc

Reputation: 13194

If you're using the MVVM pattern, which is mandatory in every serious WPF application, 'ICommand' is the way to go for every action that is not purely interface logic.

I'll explain:

As you probably know, the MVVM pattern distinguishes between Model, ViewModel and View, where the ViewModel mediates between Model and View. The ViewModel usually holds all the data which is consumed by the view and which you bind your view to. The important thing is:

The View is agnostic of the ViewModel

This means, although your View is bound to the ViewModel, it doesn't reference it, there is no logical dependency to the ViewModel. The 'ICommand' bridges this gap: It kind of packs an action into a bindable property. That's the main point, probably:

A command wraps up an action or function into a WPF databindable property

And as databinding is the mechanism which, in MVVM, View and ViewModel are connected with each other, the command is the vehicle to perform every action, no matter if it is triggered by one control or by many, that transcends the sphere of pure UI (which is almost everything):

Have a look here (MSDN), where this image is taken from:

MVVM

If you don't use MVVM I'm not sure whether you need commands at all. There is no significant difference to WinForms then, regarding the UI event handling. But again: MVVM and WPF go hand in hand, in my opinion.

Upvotes: 3

Related Questions