Page 5 of 5
Routed events – good or bad
Clearly routed events are a flexible addition to our toolkit but you have to stop and wonder if it really is worth the added confusion caused by supporting and having to learn about two different sorts of event.
As most events are indeed tied to visual components it probably makes reasonable sense to think in terms of routed events at all times – or at least wherever possible. On the other hand the structural problems that can be caused by allowing events to be handled in such a free way are potentially serious.
Imagine that you are presented with some code that you have never seen before and you task is to discover what happens when a button is clicked? Clearly nothing happens as there is no event handler added within the code in the neighbourhood of the button’s creation. Where else should you look to find a handler?
This problem is made worse by the spilt into XAML markup and code “behind”.
Internals - WPF and message passing
WFP makes some deeper changes to the way events are implemented.
Normally events are a wrapper for particular Windows messages being passed from one window to another. When you click on a button, which is just a special type of window, a message is generated which is passed to other windows. A single application will generally consist of lots of windows each with its own window handle Hwnd and message passing mechanism.
WPF changes all of this ancient machinery.
A WPF application has a single top-level window and all of the other visible entities are implemented as a graphic without a separate Hwnd. All event handling is performed by the WPF system and it has nothing at all to do with message passing apart from the initial message generated by the top-level window to indicate that the user has clicked some region of the window.
Does this change to the internal workings of the event system really matter?
In most cases the answer is probably no – after all it doesn’t generally make any difference how a click is turned into a software event.
There are two areas where you need to be careful, however. The first is any interoperability that you plan to make use of between WPF and Windows forms. Windows forms and controls are full windows complete with window handles and message handling. To mix WPF and Windows forms involves putting elements into the entity tree that have hWnds and this can be messy.
The second area is any use of the traditional approach to automating the use of an application by sending it Windows messages. There is no point in trying to send a MouseDown message to a button in a WPF application because the button isn’t a window and messages can only be sent to windows (that have window handles). As this use of message passing was never an acknowledged standard way of doing anything, you can’t really complain that it is now, and increasingly in the future, broken – but it there is no equivalent way of automating a WPF application unless it is designed into the code.