How to show a divider between items in a ListBox?

2020-04-07 18:58发布

问题:

I am using a ListBox control in a Windows Phone 7 application, and I would like to show a divider/line between the list rows. I have not been able to find any information about this, although many (not wp7) ListBox examples seem to have a divider.

回答1:

Got inspired by NestorArturo and found out about the Border control.

It is very easy to wrap your ItemTemplate content in a Border control and specify the BorderThickness and BorderBrush. I went this way, because it doesn't require changes to my Grid in the ItemTemplate.

The Border control is described here: http://www.silverlightshow.net/items/Using-the-Border-control-in-Silverlight-2-Beta-1-.aspx.

Below you can see how I use it:

<ListBox Background="White" ItemsSource="{Binding Mode=OneWay, Path=MyPath}" Name="listName" SelectionChanged="listName_SelectionChanged">
                    <ListBox.ItemContainerStyle>
                        <Style TargetType="ListBoxItem">
                            <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
                        </Style>
                    </ListBox.ItemContainerStyle>
                    <ListBox.ItemTemplate>
                        <DataTemplate>
here -->                     <Border BorderThickness="0,10,0,10" BorderBrush="Black">
                            <Grid Width="auto" HorizontalAlignment="Stretch" >
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="auto" />
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="48" />
                                </Grid.ColumnDefinitions>
                                <TextBlock VerticalAlignment="Center" FontSize="36" FontWeight="Bold" Grid.Column="0" Foreground="Black" Text="{Binding Path=Title}" Name="title"/>
                                <TextBlock VerticalAlignment="Center" HorizontalAlignment="Right" Grid.Column="1" Foreground="Black" Text="{Binding Path=Location}" Name="location"/>
                                <Image VerticalAlignment="Center" Grid.Column="2" Width="48" Height="48" Source="ApplicationIcon.jpg"/>
                            </Grid>
and here -->                </Border>
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>


回答2:

You can either change the ListBoxItem template, or, an easier approach is to change your ItemTemplate, You can simply add a divider within your ItemTemplate as follows:

<ListBox.ItemTemplate>
  <DataTemplate>
    <Grid>
       <!-- your content goes here ... for example: -->
       <TextBlock Text={Binding Path=InterestingThing}"/>

       <!-- the divider -->
       <Line X1="0" X2="200" Y1="0" Y2="0"
             VerticalAlignment="Bottom"/>
    </Grid>
  </DataTemplate>
</ListBox.ItemTemplate>