Xamarin.Forms: ListView inside StackLayout: How to set height?
With the new BindableLayout
feature in Xamarin Forms 3.5 you can easily use the ItemsSource
on StackPanel
.
So, basically you can write something like this:
<StackLayout BindableLayout.ItemsSource="{Binding list}">
<BindableLayout.ItemTemplate>
<DataTemplate>
...
</DataTemplate>
</BindableLayout.ItemTemplate>
</StackLayout>
You can read more about it here: https://blog.xamarin.com/xamarin-forms-3-5-a-little-bindable-love/
The solution in my case was to put the ListView
inside a StackLayout
and then put that StackLayout
inside the main StackLayout
. Then I could set the VerticalOptions = LayoutOptions.FillAndExpand
on the inner StackLayout
(the one containing the ListView
) with the result that the ListView
got the space it needed (which of course varies depending on the data).
Here is the main code:
listView.ItemsSource = alternativeCells;
listView.ItemSelected += ListViewOnItemSelected;
var listStackLayout = new StackLayout
{
VerticalOptions = LayoutOptions.FillAndExpand,
Orientation = StackOrientation.Vertical
};
listStackLayout.Children.Add(listView);
_stackLayout.Children.Add(listStackLayout);
As you see, I added a new StackLayout
with the only purpose of putting the ListView
inside it. Then I put that listStackLayout
inside the main _stackLayout
.
See the post on this Xamarin forum post for more information