0

We can have an object reference and we can directly invoke its method in WPF. Then why do we need commands ?

WPF Commands too mean the same thing that is giving command to an object. For example an A/C might get command to start itself from various sources like HAND, REMOTE CONTROL etc. If we are modelling an A/C, then to switch on/off it we need its reference without which we can't perform operations(invoke methods on it).

pokrate
  • 3,954
  • 7
  • 30
  • 36

2 Answers2

0

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.

Nitin
  • 18,344
  • 2
  • 36
  • 53
0

WPF Commands can only be explained meaningfully if you have a basic understanding of what MVVM means. The topic is too broad and cannot be discussed in a few posts/answers.

Here a few links which might help you understand the purpose of WPF commands and how to use them, and some tidbits about MVVM too:

Commands in MVVM
What is the difference between WPF Command and Event in WPF?
Commanding Overview
Understanding Routed Events and Commands In WPF
Implementing the MVVM Pattern
Wikipedia: MVVM

Commands are one type of interactions between the View and the "View Model" without introducing dependecies. Delegates or event handlers would mean code/compile/test dependencies between the View, the "View Model and/or the "Model" -- something you want to avoid when using the MVVM pattern.

Community
  • 1
  • 1