Search code examples
wpfitemscontrolfencepost

Getting round the fencepost principle in a WPF ItemsControl


I've got an ItemsControl with an item DataTemplate that includes a Margin value of 0,0,0,20 to add a 20-pixel gap between each item. The problem is, when this control is scrolling, there's a spare 20px after the final item caused by this margin being applied to the final item.

How do I remove/clip this gap at the end, or ensure it is not added in the first place? ie, apply a 20px gap between items but not at the start or end of the list?


Solution

  • On the ItemsPanelTemplate, set the Margin property to "0,0,0,-20".

    Example:

    <Grid Background="Black">
        <ItemsControl ItemsSource="abcdefg" Background="White" VerticalAlignment="Top">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <Border Margin="0,0,0,20" Background="Silver">
                        <TextBlock Text="{Binding}" Margin="5" />
                    </Border>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Margin="0,0,0,-20" />
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Grid>