views:

578

answers:

2

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.

+2  A: 

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>
Jobi Joy
I like the simplicity of this solution, but using a negative margin affects the layout of adjacent controls (in my case, cutting off text content). Instead, I've used negative top and bottom `Padding` on the `ListBox`, to good effect.
Jay
The idea of negative padding is a little counterintuitive, but it makes for a really straightforward and simple solution.
Robert Rossney
Yeah you need to make it proper, I just showed a less effort idea to go with. Whatever the Top and bottom margin you wish to give to the child elements, give the same but negative on the ListBox.ControlTemplate visual.
Jobi Joy
+1  A: 

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

Thomas Levesque
+1 Thanks; this is a good solution; it is just more than I want to be necessary when the only styling difference is the surrounding whitespace.
Jay