Monday, May 30, 2011

How to use ItemsControl In silverlight applications

While working on a new project I had to evluate use of Silverlight controls to replace existing ASP.Net controls and lot of javascript. One of the features of the application required listing of search results in a list. In ASP.Net application I am using Repeater control so I could control rendering of individual results through a custom template. After digging around in Silverlight documentation I found that ItemsControl provides the same features as Repeater control. This article series is to demonstrate how to use ItemsControl in Silverlight applications. This first article will demonstrate following features.

How to use ItemsControl silverlight control?
How to call into Amazon.com web services to search for products?
In next set of articles I will demonstrate how you can control rendering of items in ItemsControl and more advanced use of the control.

What is ItemsControl?
You can read more about basics of this control in Silverlight control. I will summarize it as a control that you can bind to your data (collections) to display list of items. At the heart of this control are following items that you will need to provide bare minimum meaningful implementation.

<ItemsControl>
<ItemsControl.Template>
<ItemsPresenter></ItemsPresenter>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate />
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate />
</ItemsControl.ItemTemplate>
</ItemsControl>

ItemsControl.Template is used to specify template for shell of the control. For example if you want that your list should have a border or should have some background or to specify font for all elements of list, you can specify those attributes in this block. For example in my case, I wanted to display a blue border around the list and want to make sure that vertical scrollbar appears if number of items do not fit in the specified height for this control. XAML for my example looks like following.

<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<Border BorderBrush="Blue" BorderThickness="1">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<ItemsPresenter />
</ScrollViewer>
</Border>
</ControlTemplate>
</ItemsControl.Template>

Read more: ByteBlocks