Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add space between items in a WPF/Silverlight ListBox without space above first or below last

Is there a standard/best way to space items in a WPF ListBox, such that there is space between consecutive items, but not above the first or below the last?

To me, the most obvious way to add spacing is to modify the ItemTemplate to include space above, below, or both above and below each item. This, of course, means that there will be space above/below the first and/or last item, too, or a single item.

I could use triggers to select different templates for first, last, intermediate items, but wonder if there is something simpler that I'm missing -- seems that controlling spacing would be a common requirement.

Thanks.

NOTE: I am working in WPF, but assume this is similar if not identical in Silverlight XAML.

like image 642
Jay Avatar asked Mar 22 '10 16:03

Jay


2 Answers

What I would do is, Give negative margin on the ListBox control template, and give the same margin to the DataTemplate/ItemContainerStyle. which make the space in the first and last items. Check the below XAML. Instead setting in the DataTemplate I have given margin to the Button(ListBoxItem) itself.

   <Windows.Resources> 
     <ControlTemplate x:Key="ListBoxControlTemplate1" TargetType="{x:Type ListBox}">
        <Grid Background="{TemplateBinding Background}">
            <ItemsPresenter Margin="0,-5"/>
        </Grid>
       </ControlTemplate>
   </Window.Resources>


  <ListBox HorizontalAlignment="Center" VerticalAlignment="Center" Template="{DynamicResource ListBoxControlTemplate1}" Background="#FFAB0000">
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
        <Button Content="Button" Width="88" Margin="0,5"/>
    </ListBox>
like image 75
Jobi Joy Avatar answered Sep 21 '22 16:09

Jobi Joy


You could use a StyleSelector and assign it to the ItemContainerStyleSelector property. In the style selector, you just choose a different style based on whether the item is the first, last or other

like image 2
Thomas Levesque Avatar answered Sep 19 '22 16:09

Thomas Levesque