Steven's profileDevelopmentalBlogLists Tools Help

Blog


    May 24

    WPF ListViewItem – Stretch to take the full width

    I’m doing a bit of WPF at the moment for a company in Sydney and also working on a WPF project in my spare time. Tonight I came across this issue and thought I’d document the simple solution in case I run into it again in the future.

    I have a ListView that takes up the full width of my window. I’ve edited the ListViewItem template to put a border around the items. The code looked like this:

    <ListView BorderThickness="0">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                                <Border Margin="10" Padding="8" BorderBrush="Red" Background="GhostWhite" CornerRadius="12">
                                              ……. my content here ….
                                </Border>
                        </DataTemplate>
                    </ListView.ItemTemplate>
    </ListView>

    The problem was that the border was only as big as the content inside it, even though the listview was the width of the window. What I wanted was to show an equal sized border for each item despite the size of the content inside.

    The solution in the end was really quite simple: to add the HorizontalContentAlignment="Stretch" attribute to the ListView declaration. Easy!