Fun with ItemsControl


Silverlight Logo

I spend a bit of time on the Silverlight forums and I've noticed a trend recently. A number of people are trying to get the ListBox to behave like something other than a ListBox. Most often I find it when someone is trying to handle mouse effects for items in a DataTemplate in a ListBox. What's interesting about that is that many are surprised by the neat little ItemsControl control.

For example, here I have a small little Silverlight app that shows some XBox games in a scrollable horizontal list:

Get Microsoft Silverlight

Notice that in this example I don't care about the 'selected' behavior and/or look and feel of the ListBox. I just want to display a series of items. I might want to do a pop-up when someone hovers over an item or even use things like hyperlinks in the items.  In these cases using a ListBox can become a problem because the ListBox wants to handle mouse events instead of handing them to me.  That's where the ItemsControl comes in.

The ItemsControl element is actually the base class of the ListBox and ComboBox so the API should be familiar:

<ItemsControl ItemsSource="{StaticResource theGames}">
      <Border BorderBrush="Black"
        <StackPanel Width="150"
          <Image Source="{Binding ProductImageUrl}"
                 Width="80" />
          <TextBlock Text="{Binding ProductName}"
                     FontSize="14" />

Notice the ItemsControl uses the same ItemsSource property and ItemTemplate that you're probably already using in your ListBox. Next we can use the ItemsPanel property to change the orientation of the control to be horizontal instead of vertical (notice the horizontal StackPanel that does this for us):

    <StackPanel Orientation="Horizontal"
                HorizontalAlignment="Center" />

Lastly, we can surround it all with a ScrollViewer to give it the scrolling effect we might get from the ListBox:

<ScrollViewer ScrollViewer.HorizontalScrollBarVisibility="Visible"
  <ItemsControl ItemsSource="{StaticResource theGames}">
    <!-- ... -->

If your interested in how this all works together at runtime, go grab the source code and play around with it.  But take my advice and if you are looking for something similar to the ASP.NET Repeater control with a lot more power, grab the ItemsControl and go to town! 

Application Name WilderBlog Environment Name Production
Application Ver Runtime Framework .NETCoreApp,Version=v1.1
App Path D:\home\site\wwwroot Runtime Version .NET Core 4.6.25009.03
Operating System Microsoft Windows 6.2.9200 Runtime Arch X86