Silverlight, Telerik GridView, Dynamically Created Loaded Handler & Performance

I like Silverlight, Telerik’s GridView control and the ability to create the columns of a grid dynamically.

Recently, I had to build up a grid during runtime. The number of columns and the header text is unknown at design time (read it from the database), but nothing to worry about. The XAML file only contains the definition of the Telerik grid control itself, but no column definitions.

Almost every column should contain a checkbox. And I need to handle the load event of every dynamically created checkox. Since I had to use Silverlight 4, I needed to create the cell template by using the XamlReader loading a XAML fragment.

To verify that the creation of the grid columns works at all, I did not include the load event handling in the XAML fragment for the first try. The application started, the grid and its columns were built as expected. Everything was fine.

Then I added the event handler to the fragment . The result contains something like this: <CheckBox Loaded="MyCheckBoxLoadedHandlerMethod"/>.

Having this little change done, opening the view containing the grid hangs in that way, that after a while IE complained the localhost was not responding any more. CPU usage went up, and memory consumption too.

What I think what happened is, that for each checkbox in the grid (in my sample 17 lines by 14 checkbox columns), an event handler instance is created either by Silverlight or the Telerik control. This seems to be such resource intensive, that it brought down IE.

Now what I had to do is to create a single event handler instance and assign it to every newly created checkbox. But how can I do that in Silverlight 4? In Silverlight 4 you cannot assign an object to a DataTemplate, except using the XamlReader approach (Silverlight 5 offers this ability).

I added a RowLoaded event handler to the grid. The handler iterates thru the cells of the row and looks for the checkbox child element. If it finds one, the one-and-only handler is assigned to the Click event.

It still takes time to show up the view, but now it works. I can’t tell what the real reason for the slowdown of the first approach is. But I found a way to get it running 🙂