Some fun with the Silverlight ListBox

Given the following XAML:

<UserControl x:Class="SilverlightApplication1.Page" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Loaded="UserControl_Loaded" 
    Width="400" Height="300"> 
    <Grid x:Name="LayoutRoot" Background="White"> 
        <ListBox x:Name="DemoList"></ListBox> 
    </Grid> 
</UserControl>


 



with the following code:



Partial Public Class Page
    Inherits UserControl

    Public Sub New()
        InitializeComponent()
    End Sub

    Private Sub UserControl_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
        For Each number In Enumerable.Range(1, 100)
            DemoList.Items.Add(number)
        Next
    End Sub
End Class

We end up with the following Silverlight application.

image



 



No big deal but suppose we want to have the list scroll horizontally instead of vertically?



Turns out this is quite easy but, at least to me, not all that obvious. The problem is that we need to update the ItemsPanelTemplate and Blend doesn’t seem to let me do that. However using Visual Studio its a breeze.



All we need to do is change the XAML a bit like this. The bold lines are the newly added ones.



<UserControl x:Class="SilverlightApplication1.Page" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Loaded="UserControl_Loaded" 
    Width="400" Height="300"> 
    <Grid x:Name="LayoutRoot" Background="White"> 
        <ListBox x:Name="DemoList"> 
            <ListBox.ItemsPanel> 
                <ItemsPanelTemplate> 
                    <StackPanel Orientation="Horizontal" /> 
                </ItemsPanelTemplate> 
            </ListBox.ItemsPanel> 
        </ListBox> 
    </Grid> 
</UserControl>


And we get the following layout:



image



 



Easy right [:)]



[f1]
[f2]

One thought on “Some fun with the Silverlight ListBox

  1. Instead of a for loop to populate your listbox, why not use data binding?

    DemoList.ItemsSource = Enumerable.Range(0, 100);

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>