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.
Commands provide two main benefits over event handlers:
- commands are not linked to the caller, so same command is not dependent and can be called from menu item, toolbar button, keyboard, etc.
- 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)
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.
Commands are a more standard way to integrate events. the can be more usefull than events because with the help of them you can define a single task (command) and use it from different places. for example you can define a save command and use a menu item, a context menu item and a button to use it at the same time. this way you can centerlize the tasks. also commands support data-binding which is a very powerfull feature of WPF application. as far as I know, commands lead to certain kinds of memory leaks but you can avoid that by using many work arounds. I must add that MVVM design pattern also uses commands as a standard way to design WPF application. working with events is much simpler but commands provide much powerfull design. but you must now that you can't always use commands instead of events. there any many places that you can only use events.
Additionally WPF4.0 allows binding to command definitions. This makes it even easier to expose commands from your view models, utlimately helping you in separating logic from UI concerns.
© 2022 - 2024 — McMap. All rights reserved.