如何在Xamarin.Form中将ListView的高度设置为等于所有它的ListViewItems的高度?

时间:2017-02-20 12:12:25

标签: c# listview xamarin.forms

看起来我只需将ListView的高度设置为等于Items的倍数乘以Items的高度。

但是如何获得ListViewItem的高度?

myListView.RowHeight只显示-1

我以这种方式声明ListView

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
};

我使用以下结构(我不使用XAML):

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

我的网页看起来如何以0 ListViewItems显示(ListView的大小不会随着值的数量而变化):

enter image description here

2 个答案:

答案 0 :(得分:1)

您的ListView VerticalOptions不应该设置为LayoutOptions.FillAndExpand,以便扩展到适合所有孩子吗?

<强>更新

您的LayoutOptions应仅设为Fill,无需展开。它适合您的屏幕高度或布局,如果您定义一个。

代码:

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;

答案 1 :(得分:0)

这段代码对我的项目很有用,但我非常怀疑这是一个很好的做法。

myListView.RequestHeight = number_of_items * 45;