Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between WPF Command and Event?

What is the difference between WPF Command and Event?

like image 519
Jeevan Bhatt Avatar asked Sep 20 '10 08:09

Jeevan Bhatt


People also ask

What is the difference between command and event?

What the event and the command have in common? Both are messages. They convey specific information; a command about the intent to do something, or an event about the fact that happened.

What is a WPF command?

Commanding is an input mechanism in Windows Presentation Foundation (WPF) which provides input handling at a more semantic level than device input. Examples of commands are the Copy, Cut, and Paste operations found on many applications.

Why would you want to use routed commands instead of events?

Routed commands give you three main things on top of normal event handling: Routed command source elements (invokers) can be decoupled from command targets (handlers)—they do not need direct references to one another, as they would if they were linked by an event handler.

What are events in WPF?

WPF input events are generally implemented as a preview and bubbling pairs. Direct: Only event handlers on the event source are invoked. This non-routing strategy is analogous to Windows Forms UI framework events, which are standard CLR events.


2 Answers

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.

like image 57
testalino Avatar answered Nov 10 '22 21:11

testalino


Commands are similar to Events except we can associate any number of UI Controls or Input Gestures to a command and bind that command to a handler that is executed when control are activated or gestures are performed.

Command also keep track weather or not they are available. If they are not available then all controls associated with that command are disabled.

The Code that executes when command is invoked is located in commands Execute event handler. The Code that determines is command can be or can not be invoked is located in commands CanExecute event handler.

WPF have some inbuilt Commands:

Command Class          | Example Commands
-----------------------------------------------
ApplicationCommands    | Close, Cut, Copy, Paste, Save, Print
NavigationCommands     | BrowseForward, BrowseBack, Zoom, Search
EditingCommands        | AlignXXX, MoveXXX, SelectXXX
MediaCommands          | Play, Pause, NextTrack, IncreaseVolume, Record, Stop
like image 23
Raj Avatar answered Nov 10 '22 21:11

Raj