【问题标题】:How to make ListView height dynamic?如何使 ListView 高度动态化?
【发布时间】:2017-05-17 10:32:49
【问题描述】:

我有一个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>

【问题讨论】:

    标签: c# xaml listview xamarin.forms


    【解决方案1】:

    我建议使用Grid 而不是StackLayout。确保包含ListViewRow 设置为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; }
    }
    

    这将使所有RowsHeight="Auto" 占用其内容所需的空间,而包含ListViewRow 将填满所有剩余空间。

    【讨论】:

    • 我试过了,但随着列表的增长,最后一行没有下降
    • @AlfieMcNarutoad 我编辑了我的帖子。现在单击按钮将向列表视图添加一个新项目。我不明白你的意思是最后一行没有下降。添加新项目时您希望发生什么?
    • @AlfieMcNarutoad 您可以尝试将包含 ListView 的行的高度设置为Auto 吗?这能解决您的问题吗?
    • 我之前也尝试过,但没有运气。我认为这可以追溯到非托管和托管布局规则
    猜你喜欢
    • 2018-09-19
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2020-07-09
    • 1970-01-01
    相关资源
    最近更新 更多