Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a Xamarin ListView to automatically size its rows without resizing the screen?

I have a ListView in my Xamarin app, defined like so:

        listView = new ListView
        {
            HorizontalOptions = LayoutOptions.Fill,
            HasUnevenRows = true,
            RowHeight = -1,
            ItemTemplate = new DataTemplate(() =>
            {
                var nameLabel = new Label
                {
                    VerticalOptions = LayoutOptions.Center,
                    HorizontalTextAlignment = TextAlignment.Start
                };
                nameLabel.SetBinding(Label.TextProperty, "DisplayName");

                var statusLabel = new Label 
                {
                    VerticalOptions = LayoutOptions.Center,
                    HorizontalTextAlignment = TextAlignment.End
                };
                statusLabel.SetBinding(Label.TextProperty, "Status");

                var grid = new Grid
                {
                    HorizontalOptions = LayoutOptions.Fill,
                    RowDefinitions = {
                        new RowDefinition { Height = GridLength.Auto }
                    },
                    ColumnDefinitions = {
                        new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) },
                        new ColumnDefinition { Width = GridLength.Auto }
                    }
                };

                grid.Children.Add(nameLabel, 0, 0);
                grid.Children.Add(statusLabel, 1, 0);

                return new ViewCell
                {
                    View = grid
                };
            })
        };

When I first set its ItemsSource property, the rows are clipped like so:

ListView with clipped rows

If I resize the screen, they get resized to the correct size:

ListView with resized rows

If I change the ItemsSource again, they go back to being clipped. Calling UpdateChildrenLayout or ForceLayout has no effect.

How do I get the ListView to size its rows correctly, without having to ask the user to resize their window? That's going to be a tough ask on mobile!

like image 253
Simon Avatar asked Sep 14 '25 17:09

Simon


1 Answers

If the ListView is a full screen one then set VerticalOptions=FillAndExpand. Do not set the RowHeight statically. Since you have HasUnevenRows=true it would size different rows differently based on the size of the content inside it. Also provide the VerticalOptions for the controls inside the ItemTemplate of listview, so that they will be sized properly.

like image 94
Rohit Vipin Mathews Avatar answered Sep 16 '25 06:09

Rohit Vipin Mathews