|
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>
Comments on this article
Show all comments
 |
| Se122 | |
|
| Commented on 1.June 2009 |
| I understand the concept of styles with this, but I didnt understand how you made the number to come to the left, and the text to stay on left.
|
|
|
 |
| Patrick | |
|
| Commented on 5.August 2009 |
Hi,
How can i apply animation for a selected listitem? Such as the zone out the selected itme.
|
|
|
 |
| Garry | |
|
| Commented on 9.April 2010 |
Se122,
He was able to accomplish that by setting up a grid in the datatemplate with 2 columns. 1 Column for the text aligned to the left and one column for the numbers aligned to the right.
<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>
|
|
|
|