Alex Rivera | Logout

Is it possible to emulate border-collapse (ala CSS) in a WPF ItemsControl?

Asked 2010-12-31T22:58:24.597
14

I'm styling the items in a WPF ListBox, and want to put a border around each item. With BorderThickness set to 1, for example, the top-bottom borders between adjacent items are both drawn and therefore appear "thicker" than the side borders, as shown:

ListBoxItem border example

The item template that produces these ListBoxItems is:

<DataTemplate>
  <Border BorderThickness="1" BorderBrush="DarkSlateGray" Background="DimGray" Padding="8 4 8 4">        
    <TextBlock Text="{Binding Name}" FontSize="16"/>
  </Border>
</DataTemplate>

I'd like to "collapse" these adjacent borders, as one could, for example, through CSS. I'm aware that BorderThickness can be defined separately for the left/right/top/bottom borders, but this affects the border of the first or last item, as well, which is not desired.

Is there a way to accomplish this with WPF? A property of Border I'm missing, or does it require a different approach to creating borders?

Edit
Report

1 Answer

1

One thing that comes to mind is to make use of AlternationIndex. This will require you to set something like AlternationCount="10000" on the ListBox. After that you can set BorderThickess="1,0,1,1" and use a DataTrigger to find the first ListBoxItem

<DataTemplate>
  <Border x:Name="border" BorderThickness="1,0,1,1" BorderBrush="DarkSlateGray" Background="DimGray" Padding="8 4 8 4">        
    <TextBlock Text="{Binding Name}" FontSize="16"/>
  </Border>
  <DataTemplate.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}},
                                   Path=(ItemsControl.AlternationIndex)}"
                 Value="0">
      <Setter TargetName="border" Property="BorderThickness" Value="1,1,1,1"/>
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>
answered 2011-01-01T14:24:29.790

Your Answer