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"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        
        Title="Stretch demo" Height="260" Width="250"
        Loaded="Window_Loaded"
        >
    <ListBox x:Name="lbMain"> 
        <ListBox.Style>
            <Style>
                <Setter Property="ListBoxItem.HorizontalContentAlignment" Value="Stretch" />
            </Style>
        </ListBox.Style>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Label Background="Yellow" 
                       Content="{Binding}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

Before: After:

No comments:

Post a Comment