【问题标题】:How to update Listview for each new entry at the bottom?如何为底部的每个新条目更新 Listview?
【发布时间】:2021-04-19 14:37:23
【问题描述】:

我正在制作一个带有聊天功能的应用程序,我想要实现的是对于每条新消息,底部的Listview 都会更新。这是我尝试过的:

 private ViewModel viewModel { get; set; }
    protected override async void OnAppearing()
    {
        base.OnAppearing();
        await viewModel.Connect();
        viewModel.RefreshScrollDown = () => {
            if (viewModel.Messages.Count > 0)
            {
                Device.BeginInvokeOnMainThread(() => {

                    listMessages.ScrollTo(viewModel.Messages[viewModel.Messages.Count - 1], ScrollToPosition.End, true);
                });
            }
        };
    }

列表视图:

 <ListView
            x:Name="MessagesList"
            BackgroundColor="Transparent"
            HasUnevenRows="true"
            ItemTemplate="{StaticResource chatDataTemplateSelector}"
            ItemsSource="{Binding Messages}"
            SelectionMode="None" />

当我换成CollectionView:

      <CollectionView
            x:Name="MessagesList"
            BackgroundColor="Transparent"
            ItemTemplate="{StaticResource chatDataTemplateSelector}"
            ItemsSource="{Binding Messages}"
            ItemsUpdatingScrollMode="KeepLastItemInView"
            SelectionMode="None" />

【问题讨论】:

  • 您是在问如何将新数据实际添加到您的列表视图中?你的 ItemsSourceObservableCollection 吗?
  • 我的 ItemSource 是一个 ObservableCollection。我问如何在收到新消息时将列表视图滚动到底部。
  • 您的代码有什么问题?它做什么(或不做什么)?
  • OnAppearing 仅在您导航到页面时发生。如果您仅在同一页面上添加到您的收藏,那么这就是它不起作用的原因 - 您需要将该 ScrollTo 代码放在您添加到收藏的同一位置。
  • 我现在正在测试,但从未调用 RefreshScrollDown。

标签: c# listview xamarin.forms


【解决方案1】:

如果您将新消息添加到您的ItemSource,那么您可以考虑使用CollectionView,因为它有一个现成的属性(ItemsUpdatingScrollMode="KeepLastItemInView")可以调整滚动偏移以保持添加新项目时显示的列表中的最后一项。

你可以看看Control scroll position when new items are added

更新:

在列表视图中,您的 DataTemplate 可能像:

<ListView.ItemTemplate>
   <DataTemplate>
      <ViewCell>
        <Grid>
         ...
        </Grid>
      </ViewCell>
   </DataTemplate>
</ListView.ItemTemplate>

当你使用collectionview时,会是这样的:

<CollectionView.ItemTemplate>
  <DataTemplate>
    <Grid>
     ...
    </Grid>
  </DataTemplate>
</CollectionView.ItemTemplate>

您可以参考collectionview

【讨论】:

  • 我已从 ListView 更改为 CollectionView,我的应用程序因以下错误而崩溃: System.InvalidCastException: 'Specified cast is not valid.'
  • @dimioLt 你能显示引发异常的代码吗?
  • 应用程序在启动 2 秒后崩溃,并且该异常没有显示它发生的任何行。有什么办法可以清楚的知道吗?我对调试了解不多
  • @dimioLt 更改 ListView 后是否崩溃?如果是这样,您可以显示页面的代码。
  • 是的,使用 ListView 它可以正常工作,但是当更改为 CollectionView 时它会崩溃。我用 ListView 和 CollectionView 的代码更新了帖子。
猜你喜欢
  • 2021-11-06
  • 1970-01-01
  • 2020-06-27
  • 1970-01-01
  • 2013-11-10
  • 2021-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多