Silverlight 2 Tip – Declaring Events


I’ve seen a lot of demo’s and example on Silverlight 2 flying around. One are that seems to get a lot of difference of opinion is where to declare events. You can either define the event handler in XAML declaratively, or you can add the handler in the .NET code. What’s the best way?

Proponents of declaring the event handler in the XAML say anything that’s static should go in the XAML. So let’s run with that … let’s assume that the event handler needs to be added and that it won’t be removed and re-added (like you can do with code). Because obviously if that is the case, code is the place to do it. So we have this event handler declared in XAML, the upside is that its less code. Another upside is that its easy to do … just click on the properties in Blend and add the handler to the XAML.

But the downside is that functionality is now in the XAML. The XAML is often stated to be the place where designers can roam free. Are designers responsible for event handlers? I would say no, that’s for the developer. If you subscribe to the theory that XAML is where the content and design should live, not functionality. So one day you are working on your .NET code and you are wondering why an event is getting invoked. Now you have to look in the code file as well as the XAML file (when you declare events in the XAML).

Adding the event in the code adds more physical code to the process, but the upside is that all of the functionality remains in the code file. If you put all of the handler definitions in the constructor as a group, then all of them are easy to find when working with the code.

What’s my opinion? I firmly believe the handlers belong in the code and not in the XAML. I recommend putting the handlers in the code as a group, as shown below:



























public BookSearch()
btnOK.Click += new RoutedEventHandler(btnOK_Click);
btnAddToCard.Click += new RoutedEventHandler(btnAddToCard_Click);
btnClearCart.Click += new RoutedEventHandler(btnClearCart_Click);
btnRemoveItem.Click += new RoutedEventHandler(btnRemoveItem_Click);
ShoppingCart = new Cart();



Public Sub New()
AddHandler btnOK.Click, AddressOf btnOK_Click
AddHandler btnAddToCard.Click, AddressOf btnAddToCard_Click
AddHandler btnClearCart.Click, AddressOf btnClearCart_Click
AddHandler btnRemoveItem.Click, AddressOf btnRemoveItem_Click
ShoppingCart = New Cart()
End Sub

DotNetKicks Image
Tweet Post Share Update RSS

Hi, I'm John Papa. I author this blog, create courses for Pluralsight and am a Google Developer Expert and Microsoft Regional Director. I travel speaking at events and train technology thought leaders