tags:

views:

60

answers:

4

what is the difference between wpf command and event?

+1  A: 

You can bind WPF command in the view (XAML) and receive the event raised. This way you do not have to use code behind which is a no-no in MVVM.

So the binding element is very important. But it also implements CanExecute which normally makes your control disabled if it returns false, e.g. if it is a button.

Aliostad
+1  A: 

Generally speaking you can do almost the same with events as with commands, it is just a different pattern of handling user interaction.

Commands in WPF allow you to move the implementation of a command handler to the buisness layer. Commands combine Enable state and executation, so everything is in place. Reade more by searching for the MVVM pattern.

Commands are more complex to implement at first, so if your application is small you should consider just sticking to events.

testalino
Command is commonly used pattern in SOA and events are in Event driven architecture (EDA).
Liton
"Commands in WPF allow you to move the implementation of a command handler to the buisness layer." this is not true. It must be "outside the view".
Aliostad
@Aliostad IMHO, a "business layer" is in general "outside the view".
Liton
I won't agree to that; Commands is a very powerful and useful feature of WPF and provides a lot of advantages over events. If you are considering WPF seriously then you must start using commands ASAP. It really simplifies the development and is really easy to use(you will have to spend some time though).
akjoshi
@akjoshi I didn't say anything different. For small projects I just wouldn't use commands because of their overhead.
testalino
A: 

Roughly speaking, Command is encapsulation of Object (Button, Menu) Enable/Disable State and Action.

Limitation of Command:

  • Multicast (you can use multi binding but not so common and don't feel as nice as event multicast)
  • Need 2 step to light up the bulb. (If your button is always enable, then you just waste your code).
ktutnik
A: 

In events an action is tightly coupled with its source and can't be reused freely; Using commands you can easily maintain various actions in a single place and reuse them anywhere in application.

What makes commands different from a simple event handler attached to a button or a timer is that commands separate the semantics and the originator of an action from its logic. This allows for multiple and disparate sources to invoke the same command logic, and it allows the command logic to be customized for different targets.

taken from - Commanding Overview: http://msdn.microsoft.com/en-us/library/ms752308(v=VS.90).aspx

This article explains the concept of Commands and is must read before using commands.

This SO thread is also havign a lot of useful info. :

http://stackoverflow.com/questions/8452/i-dont-grok-the-wpf-command-pattern

akjoshi