简体   繁体   中英

How do I customize the layout of a ListBox's ItemsPanelTemplate?

I'd like to specify multiple columns for my ListBox , but my googling skills have failed me on this one.

How can I modify the ItemsPanelTemplate of a ListBox to customize the columns displayed?

Edit: forgot to put what I'd tried already

I've tried the code

<ItemsPanelTemplate x:Key="ItemsPanelTemplate1">
        <UniformGrid Columns="3" />
    </ItemsPanelTemplate>

Which works except I lose the vertical scrollbar

It shoudln't be that difficult but it depends - if you are using a grid or some-such control for each item and you don't mind the columns not being the same width with variable width items inside them, then just adding a grid to the ItemTemplate will do.

<ItemTemplate>
    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition>
                <ColumnDefinition>
                <ColumnDefinition>
            </Grid.ColumnDefinitions>
            <SomeControl Grid.Column="0" />
            <SomeControl Grid.Column="1" />
            <SomeControl Grid.Column="2" />
        </Grid>
    </DataTemplate>
</ItemTemplate>

The only problem is if you want the grid columns to all be the same size with variable sized content - in which case it would be a little more involved - otherwise you can either explicitly set a size, or let the content decide the size by setting the column widths to "Auto" .

Here's a simple example of what I think you're looking for, with 3 columns, item wrapping, and automatic vertical scrolling which will work depending on the surrounding layout.

<ListBox HorizontalContentAlignment="Stretch">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="3"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Border MinHeight="150" Margin="5" Background="Green" CornerRadius="4">
                <TextBlock Text="{Binding}" Foreground="White"/>
            </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>

    <System:String>One</System:String>
    <System:String>Two</System:String>
    <System:String>Three</System:String>
    <System:String>Four</System:String>
    <System:String>Five</System:String>
    <System:String>Six</System:String>
    <System:String>Seven</System:String>
    <System:String>Eight</System:String>
    <System:String>Nine</System:String>
    <System:String>Ten</System:String>
</ListBox>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM