C# WPF Events

Events can be generated by WPF controls. They can also be generated by other things such as the system timer. Another Events post discusses events raised by a timer. In WPF, whena user clicks a button that raises an event. The programmer writes code to handle that event. Many events are common to the controls you work with because the events themselves are inherited from base classes such as Control or ContentControl.

Here is an alphabetical list of common control events: click, drop, dragenter, dragleave, dragover, keydown, keyup, gotfocus, lostfocus, mousedoubleclick, mousedown, mousemove and mouseup. In the Visual Studio IDE there are two basic ways to add a handler for an event. One way is to use the Events list in the Properties window (lick the lightening bolt). You can also type the name of the event directly in XAML and add the name of the event handler there. You can then right-click on the event and choose Navigate to Event Handler to add the event handler to the code-behind file.

Routed Events

WPF uses events that are called routed events. A standard .NET event is handled by the code that has explicitly subscribed to it and it is sent only to those subscribers. Routed events are different in that they can send the event to all controls in the hierarchy in which the control participates. When an event travels up the control hierarchy like this, it is called a bobbling event.

Routed events can also travel in the other direction, that is, from the root element to the control on which the action was performed. This is called a tunneling event and by convention all events like this are prefixed with the word Preview and always occur before their bobbling counterparts. An example of this is the PreviewMouseRightButtonDown event.

Routed Commands

Routed commands serve much the same purpose as events in that they cause some code to execute. Where Events are bound directly to a single element in the XAML and a handler in the code, Routed Commands are more sophisticated. An event should be used whenever you have a piece of code that has to respond to a user action that happens in only one place in your application. An example of such an event could be when the user clicks OK in a window to save and close it. A command can be used when you have code that will be executed to respond to actions that happen in many locations. An example of this is when the content of an application is saved. There is often a menu with a Save command that can be selected, as well as a toolbar button for the same purpose. It is possible to use event handlers to do this, but it would mean implementing the same code in many locations — a command allows you to write the code just once.

Leave a comment

Your email address will not be published. Required fields are marked *