Explaining commanding
in wpf is a huge topic in itself and may take couple of pages to write. Here I will just stick to the example you have given in your question. First of all, Command
(implementation of ICommand
interface) as good as the name give to it represent the Action
to be performed. When and on which that action needs to performed depends on where and how we are using it. Basic use of command is to convey user actions on UI to corresponding ViewModels
.
In your example, if you have model name AC
, which has function Off()
. Now your UI can have multiple controls providing the rendering of this model and to perform actions on it. Lets say on screen you want to switch off AC
by click
on Button
or also using the ContextMenu
or by some keyboard
shortcut. First you need to convey these user action to the viewmodel containing your model (AC). Your xaml cannot call Off()
on your AC and doing it in code behind will mean writing handlers for each and every useraction and from those multiple handlers you will be calling the same function
Here your command will step in. You will define just one command SwitchOffACCommand
and bind it Command
of button
, MenuItem
.
You will have just one handler for the Command
where you will call AC.SwitchOff()
. If you want to modify or validate something before switching off your AC you will just be doing it in just one place.