Tuesday, May 22, 2012

Stretching and right-aligning in ListView and ListBox

It's been a few times I needed to right-align the content in a ListView, last time I tried to figure it out myself for 15 minutes and failed again. As in previous times, I found the answer some time after googling, so I decided to post the solution here in order not to forget again.

To summarize, the trick is to set ListViewItem.HorizontalContentAlignment (or the one of ListBoxItem whichever you need) to Stretch. The problem is that you probably want to use databinding (and that's the right way), so that every ListViewItem (or ListBoxItem) is virtualized under the hood. You can use styles.

The code:
<Window x:Class="StretchDemo.MainWindow"
        Title="Stretch demo" Height="260" Width="250"
    <ListBox x:Name="lbMain"> 
                <Setter Property="ListBoxItem.HorizontalContentAlignment" Value="Stretch" />
                <Label Background="Yellow" 

Before: After:

No comments:

Post a Comment