Freshek Freshek - 18 days ago 5
C# Question

How to add separator every item in ListBox?

I'm writing a music player with playlist in WPF. My playlist looks that:



But I want to get separator every one item. I tried some ways but all are done with ready data source. In my playlist I'm adding songs in code.

<ListBox
x:Name="PlaylistBox"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
HorizontalAlignment="Left"
Height="358"
Margin="19,274,0,0"
VerticalAlignment="Top"
Width="299"
Grid.ColumnSpan="2"
BorderThickness="0"
Foreground="White"
SelectionChanged="PlaylistBox_SelectionChanged"
MouseDoubleClick="PlaylistBox_MouseDoubleClick"
Background="Black"
AllowDrop="True"
Drop="PlaylistBox_Drop"/>

Answer

You can do it with an item template

In this example every item is surrounded by a partial border, drawing a line at the bottom, giving the illusion of a separator.

<ListBox x:Name="PlaylistBox" ...other properties...>
      <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderThickness="0,0,0,2" BorderBrush="Black">
                    <Label Content="{Binding}"/>
                </Border>
            </DataTemplate>
      </ListBox.ItemTemplate>
</ListBox>

<Label Content="{Binding}"/> might not work for you, since I don't know the type of your items.

This is just a very basic example, there could be a better way to do it, I'm not sure how you're populating your listbox, please read about MVVM and bind your items to a collection in a model

Comments