Articles in this section
Category / Section

How to adjust the parent height based on total items height when AutoFitMode is Height?

2 mins read

Xamarin ListView(SfListView) allows us to adjust the parent height based on bind items when AutoFitMode is Height by setting the height of VisualContainer to the height of StackLayout (parent for SfListView), it can be done by customizing the StackLayout as StackLayoutExt (parent for SfListView) in sample level. It will update whenever items are added or removed.

Please refer below code snippet for customizing StackLayout.

C#

public class StackLayoutExt : StackLayout
{
    public StackLayoutExt()
    {
    }
 
    public void LayoutChildren(double width, double height)
    {
        this.LayoutChildren(0, 0, width, height);
    }
 
}

 

In the above code snippet, the internal LayoutChildren method is added to set the height of parent while layout the children.

Defining SfListView inside StackLayoutExt:

XAML

<local:StackLayoutExt VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" 
                           x:Name="baseLayout" BackgroundColor="Teal">
                <syncfusion:SfListView ItemsSource="{Binding BookInfo}" ItemSize="50"
                                  x:Name="listView" BackgroundColor="Yellow"
                                  AutoFitMode="Height" SelectionMode="None">
                </syncfusion:SfListView>
</local:StackLayoutExt>

 

In the Loaded Event the total extent of VisualContainer is set as the height of StackLayout and the ItemsSource is changed with increased items which increases the height of SfListView along with the height of StackLayout.

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        listView.Loaded += ListView_Loaded;
    }
 
    private void ListView_Loaded(object sender, ListViewLoadedEventArgs e)
    {
        var visualContainer = listView.GetVisualContainer();
        var totalextent = (double)visualContainer.GetType().GetRuntimeProperties().FirstOrDefault(container => container.Name == "TotalExtent").GetValue(visualContainer);
        var parent = new StackLayoutExt();
        parent.LayoutChildren(this.Width, totalextent);
    }
 
    private void ChangeItemsSource_Clicked(object sender, EventArgs e)
    {
        this.viewModel.add();
        var visualContainer = listView.GetVisualContainer();
        baseLayout.HeightRequest = visualContainer.Height;
    }
}

 

Click here to download the sample

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied