I have this code in XAML
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,20">
<TextBlock x:Name="ApplicationTitle" Text="Title" />
<TextBlock x:Name="PageTitle" Text="title" Margin="9,-7,0,0" />
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="22,0,12,0">
<StackPanel>
<ListBox Name="Cities"Height="Auto" Margin="4,3,0,10">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="40" Text="{Binding Name}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Grid>
When i put items in ListBox, scroll not working. I dont want set fixed height of Listbox, because i need to support different screen resolution. I need auto height. How can i do this?
You don’t need the
StackPanel, since there’s only one child in it. The same goes for theGridnamed “ContentPanel”.Remove both of them, set
Grid.Rowon theListBoxand adjust the margins.The reason is that
StackPanelis not constraining the height of its children, whatever the height your list box is asking for – stack panel provides it, even if means that the list box will not be fully shown. Since the list box is getting all the height it wants, it figures that there’s no need for scrolling. This is a simplification of what is actually happens, but it’s enough to understand what is happening.StackPanelis kind of “evil” in that regard – it will silently give any height the child wants.You don’t have to remove the grid for the UI to work, but you also don’t need it. Less nesting is better.