WrapPanel in ListBox revisited

Last week logged about using a WrapPanel in a listBox and demonstrated how to get the content to wrap around, read about it here.

Turns out the XAML can be even easier. In the previous post I used a ControlTemplate with a Grid to stop the WrapPanel from just expanding horizontally. Turns out there us an even easier way to do so by disabling the horizontal scrollbar using the ListBox ScrollViewer. The following XAML will do the trick just fine:

<UserControl xmlns:controls="clr-namespace:Microsoft.Windows.Controls;assembly=Microsoft.Windows.Controls"  
             Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox x:Name="DemoList" 
                    <controls:WrapPanel />
                    <TextBlock Text="{Binding}" 
                   Width="25" />

Used in combination with the following code:

using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace SilverlightApplication4
    public partial class Page : UserControl
        public Page()
            Loaded += new RoutedEventHandler(Page_Loaded);

        void Page_Loaded(object sender, RoutedEventArgs e)
            DemoList.ItemsSource = Enumerable.Range(1, 250);

it produces this Silverlight page:


We even get some keyboard support with the new XAML although I am not quite sure if I am happy about that or not. Selecting an element and pressing the down arrow key makes the selection move to the right. Makes sense in that it is the next item in the ItemsSource bit not quite what I was hoping for.

Just for a quick comparison I copied the XAML and code to a WPF application to see what would happen there. Fortunately the only change I hard to make to the ListBox was removing the controls namespace. Great [:)]


When I ran the same in WPF I do see the keyboard behavior I would like. Pressing the down arrow selects the next item below the current, the same with up and the other arrow keys and even the page up/down scroll a page but move in the same column. Now this is much better behavior!




One thought on “WrapPanel in ListBox revisited

  1. Thanks a lot for the post .. the ScrollBarVisibility is such a big misnomer … I thought it was just to deal with visibility …

Leave a Reply

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