Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Saturday, July 7, 2012

How to strech an WPF ListBox Item to span the whole width

If you create a data template with a right-aligned element (like the age in our exmple), it only spans over the needed width, because the content of a listbox is left-aligned by default.
This is the DataTemplate I created for this example.
 
<Style TargetType="ListBox" x:Key="strechedItemStyle">
    <Setter Property="ItemTemplate">
        <Setter.Value>
            <DataTemplate>
                <Grid Background="#330000FF">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="Auto" />
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <TextBlock Text="{Binding Name}" HorizontalAlignment="Left"  Grid.Column="0"/>
                    <TextBlock Text="{Binding Age}" HorizontalAlignment="Right" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </Setter.Value>
    </Setter>
</Style>
 
 
To make the listbox item span the whole width of the listbox you need to set the HorizontalContentAlignment property to Stretch.
This is the way to set it directly on the listbox element:
 
<ListBox x:Name="listBox" Margin="20" 
         Style="{StaticResource strechedItemStyle}" 
         HorizontalContentAlignment="Stretch" />
 
 
If you want to set this property within a style you can do it with the following lines of code
 
<Style TargetType="ListBox" x:Key="strechedItemStyle">
  <Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>

No comments:

Post a Comment