|
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>
Comments on this article
Show all comments
 |
| eldose | |
|
| Commented on 25.January 2010 |
| very simple to study by using this tips
|
|
|
 |
| janu | |
|
| Commented on 10.August 2010 |
| good
|
|
|
 |
| hero | |
|
| Commented on 25.August 2010 |
| Very good, very very good!
|
|
|
|