rupertmulrenan
rupertmulrenan

Reputation: 355

How to fix layout of list box with custom item template

I have applied a custom ItemTemplate to the ListBox control, but have an issue with the layout. When the ListBox is scrolled to the bottom and is resized the item overflows:

ListBox Layout Issue

It seems that if i scroll up the layout is eventually corrected:

ListBox Corrected

If i remove the line which sets the HorizontalContentAlignment the issue goes away (but i would like the list item to stretch to fill the available space)...

Any help would be appreciated.

<ListBox x:Name="myList" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Visible">
        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="HorizontalContentAlignment"  Value="Stretch"></Setter>
            </Style>
        </ListBox.ItemContainerStyle>            
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>

                    <TextBlock Background="Lime" TextWrapping="Wrap" Text="{Binding Comments}"/>
                    <Grid Grid.Column="1" Background="Aqua">
                        <Button Width="20" Height="20" Content="..."/>
                    </Grid>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Upvotes: 2

Views: 87

Answers (1)

Funk
Funk

Reputation: 11211

The default ItemsPanel of a ListBox is a VirtualizingStackPanel, which copes badly with the Stretch alignment. Instead, try a UniformGrid with just one column.

<ListBox.ItemsPanel>
    <ItemsPanelTemplate>
        <UniformGrid Columns="1"/>
    </ItemsPanelTemplate>
</ListBox.ItemsPanel>

Upvotes: 1

Related Questions