How to Customize an ItemsControl

If you are a Silverlight developer there will be a moment when you’ll look at a ListBox and not be happy with its default behavior. You are not exactly a beginner – you know how to modify the style or the template for a control and even how to write your own custom controls. Depending on what changes are needed you’ll consider different solutions. Modifying the style and template of the ListBox comes to mind but it is not very clear how to achieve some of the customizations even if you are willing to modify the template of the ListBox. If the changes you need are substantial you may be willing to write a custom control but in the case of a ListBox this appears to be more difficult than expected. A ListBox is not just a simple control. It is a container that manages a collection. And it is more than a container in the sense that a Grid or a Canvas are containers. A ListBox has an ItemsSource that can be bound to a data source. Writing a custom ListBox is quite different than writing a custom Panel.

You will see that in most cases customizing a list is not that hard. A couple of things are worth mentioning from the start. First, there are plenty of ways you can customize a ListBox without needing to write a custom control. Second, the main subject of this story is the class ItemsControl and not ListBox. You may be more familiar with the ListBox but most of the concepts we are going to analyze belong to the ItemsControl. If you need to write your own custom list it is much more likely that you’ll inherit your class from ItemsControl rather than from ListBox.

The examples discussed in this article are illustrated in a sample Silverlight application you can view at ItemsControlDemo.
You can download the code from ItemsControlDemo.zip.

Read the full article.

Leave a comment