Where do you "event"?

From JohnPapa.net, “Siliverlight 2-Tip – Declaring Events.”

He thinks that the place to wire up an event is always in code rather than in markup (like XAML).

“What’s my opinion? I firmly believe the handlers belong in the code and not in the XAML.”

I’d suggest that’s not always right either (and maybe not the right question to ask). This technique doesn’t allow the designer to have freedom to decide how to build the interface freely. If you wire up to a “button” click, then the designer has to implement a certain UI feature as a button. Maybe that’s not what they wanted. The UI/code are wound together extremely tightly when using this pattern.

A command/message driven architecture that splits the actual implementation as much as possible is the best pattern for growth and true separation of roles. That being said, it’s not always practical to build a system like that.

I like the CONCEPT of WPF’s RoutedCommand system which is a way in WPF to handle this pattern, but I don’t care for the way that things are enabled and disabled via the CanExecute event handlers. The event handlers can be called hundreds of times a minute depending on your user interface.

The bad news is that Silverlight doesn’t lend itself easily to a message/command driven architecture (as the RoutedCommand system isn’t available in Silverlight 2.0). So what’s a developer to do? :)

I like the ‘toolability’ of doing inline (in XAML) wire-up of events. If the developer just provides a common set of end-points (events) to the UI designer, then they may have an opportunity to more freely control and adjust the user interface as needed without requiring code changes.

So in John’s example code, instead of

btnAddToCard.Click += new RoutedEventHandler(btnAddToCard_Click);

It might be better to provide a method called:

AddToCard(object sender, RoutedEventArgs e) {


That way, the designer can wire-up any way they want.

Or, I suppose one could build a rudimentary message/command system by using attached properties and a common event handler which handles all command driven user interface elements. (And now that I think about that more — I think that could end up being quite slick if done carefully).


Comments are closed.