如何使ListView高度动态?

时间:2017-05-17 10:32:49

标签: c# xaml listview xamarin.forms

我有ListView,下面是StackLayout。我试图使ListView高度随着更多行的增加而增长(使用StackLayout中的命令)而只使用XAML。发生的事情是ListView的高度太大,页面最终可以滚动StackLayout一直向下

这是我的代码:

<StackLayout Orientation="Vertical">
     <BoxView HorizontalOptions="FillAndExpand" HeightRequest="10" Color="Transparent/>
     <StackLayout>
          <Label Style="{StaticResource AXASOL_Label_H1}" TextColor="White" Text="Do you have Dependents?" HorizontalOptions="Center"/>
     </StackLayout>
     <ListView>
          <ListView.ItemTemplate>
              <DataTemplate>
                   <ViewCell>
                   </ViewCell>
              </DataTemplate>
           </ListView.ItemTemplate>
     </ListView>
     <StackLayout Orientation="Horizontal" HorizontalOptions="Center">
     </StackLayout>
 </StackLayout>

1 个答案:

答案 0 :(得分:2)

我建议使用Grid代替StackLayout。确保包含Row的{​​{1}}设置了ListView

Height="*"

代码隐藏:

    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Content="Do you have Dependents?" />

     <ListView Grid.Row="1" ItemsSource="{Binding Items}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}" />
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
    <Button Grid.Row="2" Content="Click" Click="ButtonBase_OnClick"></Button>
</Grid>

这会使所有public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = this; Items = new ObservableCollection<Item>(); Items.Add(new Item("bla")); Items.Add(new Item("blub")); Items.Add(new Item("blubber")); } public ObservableCollection<Item> Items { get; set; } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { Items.Add(new Item("test")); } } public class Item { public Item(string name) { Name = name; } public string Name { get; set; } } Rows Height="Auto"占用内容所需的空间,而Row ListView将占用所有剩余空间。