Corrado Cavalli

I have a listbox bound to an ObservableCollection<Person>:

<Window.Resources>
<ObjectDataProvider x:Key="PersonsDS" d:IsDataSource="True"
ObjectType="{x:Type WPF_DatatemplateStick out tongueersons}"/>

<DataTemplate x:Key="PersonsTemplate">
<StackPanel Background="Yellow">
<TextBlock Text="{Binding Path=Age}"/>
<TextBlock Text="{Binding Path=Name}"/>
</StackPanel>
</DataTemplate>
</Window.Resources>

<Grid>
<ListBox ItemTemplate="{DynamicResource PersonsTemplate}"
ItemsSource="{Binding Mode=OneWay, Source={StaticResource PersonsDS}}"
Margin="49,40,63,26" ItemContainerStyle="{DynamicResource
ListBoxItemStyle1}"/>
</Grid>

Everything is fine apart that DataTemplate doesn't fit listbox width (that can change after a resize).

How can i fix this




Re: Windows Presentation Foundation (WPF) Autosizing DataTemplate

Josh Smith

Set the ItemContainerStyle to a Style which sets HorizontalContentAlignment to Stretch. That should force the content of the ListBoxItem to fill the available area.






Re: Windows Presentation Foundation (WPF) Autosizing DataTemplate

Corrado Cavalli

Even simpler:Just set Listbox's HorizontalContentAlignment to "Stretch"

Thanks Josh for the hint.






Re: Windows Presentation Foundation (WPF) Autosizing DataTemplate

Josh Smith

Corrado Cavalli wrote:

Even simpler:Just set Listbox's HorizontalContentAlignment to "Stretch"

That makes sense!