Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Saturday, July 7, 2012

Change the arrangement of items in a listbox

All WPF controls deriving from ItemsControl provide an ItemsPanel property that allows you to replace the internal layout panel that arranges the items.

Horizontal

We override the ItemsPanel property and set it to a StackPanel layout manager with an orientation set to Horizontal. We use an VirtualizingStackPanel that works just like a normal StackPanel, except that is does only create the items that are visible. If you scroll it automatically creates the new items that become visible and recycles the hidden.
 
<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>
 
 

Wrapped

Using a WrapPanel to layout the items row by row is a bit more complex. Since the layout panel is wrapped by a ScrollContentPresenter (as seen by the scrolbar of the exmple above) the available width is infinite. So the WrapPanel does not see a reason to wrap to a new line.
What we need to do is to set the width of the warp panel to the ActualWidth if the internal ScrollContentPresenter. The ScrollContentPresenter can be found by using the FindAncestor mode of the relative source extension.
 
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

No comments:

Post a Comment