Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Commands vs Events Advantages/Disadvantages

Tags:

wpf

Can anyone tell me what are the advantages of using Commands vs Events in WPF. Do Commands or Events run into memory leaks? What is the fastest approach. What are their disadvantages.

like image 621
WPF User Avatar asked Jun 01 '10 20:06

WPF User


People also ask

Why should we 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?

In a WPF application, events are often implemented as a tunneling/bubbling pair. So, you'll have a preview MouseDown and then a MouseDown event. Given below is a simple example of a Routed event in which a button and three text blocks are created with some properties and events.


2 Answers

Commands provide two main benefits over event handlers:

  1. commands are not linked to the caller, so same command is not dependent and can be called from menu item, toolbar button, keyboard, etc.
  2. commands provide support for enabling/disabling all related UI controls based on the status of command (can be executed or not)

I'd prefer using commands at real project, especially if you want to use M-V-VM.

I haven't heard about any memory leaks related with commands.

Events are probably faster, but the difference should not be significant - I've been using commands on my projects for 2 years and hadn't any performance issues with them.

For more details on commands see Commanding Overview(archive)(v4)

like image 123
Andrii Avatar answered Sep 19 '22 15:09

Andrii


But although Commands and Events can be overlapping, they are two different things. Commands say "do this!", while events say "this just happened!". So you might have a CloseWindowCommand for closing a window, but the window might have a ClosingEvent that tells subscribing objects that is is closing.

like image 41
T.J.Kjaer Avatar answered Sep 18 '22 15:09

T.J.Kjaer