In Winforms we (developers) handle user interactions via events. In WPF we got commands.
Questions :
what's difference between events in Winforms and commands in WPF? Which approach we must use? and when?
what's difference between events in Winforms and routed events in WPF?
Command represented by an object which could be serialized, passed over a process, whatever, let's say it is more "flexible".
Routed Events supports next strategies - direct, bubbling and tunneling , also using routed event you can indicate that event was processed by settign an appropriate flag in event arguments.
I'd highly recommend starting out by reading through MSDN's article on Routed Events , however from my point of view, the biggest difference is how they work
Winforms lets you assign an method to an event handler, and whenever that control's event is raised, that handler gets run. You can actually do the same thing in WPF, or you can use a Routed Event.
In a Routed Event, an event is generated (such as a click event), and the any element in the Visual Tree can subscribe to do something during the Click event, and can mark the Event as handled or not.
For example, suppose you have a Button
containing a Border
and an Image
<Button>
<Border>
<Image>
</Border>
</Button>
Clicking on the Image
doesn't execute Button.ClickEvent
, but instead simply raises a generic Click
event which is processed by the Image
first, then the Border
, and then the Button
. The event will actually continue up the VisualTree until it hits the Window
object, unless one of the controls handling the event marks it as Handled
This type of Routed event is called a Bubbling
event because the event travels, or "bubbles", up the Visual Tree. Another event type is Tunneling
, where the event travels down the VisualTree, or Direct
, where only the object that got clicked processes the event.
As for the difference between Routed Events
and Commands
, they provide two separate functions. Events are built-in and are tied with the UI object that is handling the Event, while a Command is not tied to the UI object in any way, and provides built-in support for enabling/disabling controls.
For example, a Button with a Click
event will pass the Button object into the Click event handler, while a Button with the Command
property set will execute an unrelated command and automatically enable/disable the button depending on Command.CanExecute()
I use the MVVM design pattern, so almost always use Commands (if a control doesn't support the Command
property, I use a custom Attached Command Behavior which lets me attach a command to almost any UI event), however I still use Events on occasion when I want to do something that affects the View only and doesn't do any business logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.