简体   繁体   中英

How to set height of ListView equal to height of all it's ListViewItems together in Xamarin.Form?

Looks like I just need to set height of ListView equal to a number of Items multiplied by height of Items .

But how to get height of ListViewItem ?

myListView.RowHeight just shows -1 .

I declare ListView this way:

DataTemplate dTemplate = new DataTemplate(() => {
    StackLayout sl = new StackLayout {
        VerticalOptions = LayoutOptions.FillAndExpand,
        Orientation = StackOrientation.Horizontal,
        Padding = new Thickness(20, 10, 0, 10),
        Spacing = 20
    };

    var temp = new Label { FontSize = 20 };
    temp.SetBinding(Label.TextProperty, ".");

    sl.Children.Add(temp);

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

ListView myListView = new ListView {
    VerticalOptions = LayoutOptions.FillAndExpand,
    ItemsSource = stringList,
    ItemTemplate = dTemplate
    BackgroundColor = Color.Red
};

I use following structure (I don't use XAML):

<NavigationPage>
    <ContentPage>
        <ScrollView>
            <StackLayout>
                <ListView>
                ...

That's how my page looks with 0 ListViewItems (size of ListView isn't changing with number of values):

在此处输入图片说明

Shouldn't your ListView VerticalOptions be set to LayoutOptions.FillAndExpand so that it expands to fit all of its children?

Update

Your LayoutOptions should be set to Fill only, no need to expand. It will fit your screen height or a layout, if you define one.

Code:

List<string> stringList = new List<string> { "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", "a", "b", "c", };
        DataTemplate dTemplate = new DataTemplate(() =>
        {
            StackLayout sl = new StackLayout
            {
                Orientation = StackOrientation.Horizontal,
                Padding = new Thickness(20, 10, 0, 10),
                Spacing = 20
            };

            var temp = new Label { FontSize = 20 };
            temp.SetBinding(Label.TextProperty, ".");

            sl.Children.Add(temp);

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

        ListView myListView = new ListView
        {
            VerticalOptions = LayoutOptions.Fill,
            ItemsSource = stringList,
            ItemTemplate = dTemplate,
            BackgroundColor = Color.Red
        };

        this.Content = myListView;

这段代码对我的项目来说还可以,但是我高度怀疑这是一个好习惯。

myListView.RequestHeight = number_of_items * 45;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM