【问题标题】:ListView scroll freezes when item is added in Xamarin Forms在 Xamarin 表单中添加项目时,ListView 滚动冻结
【发布时间】:2018-06-26 13:42:46
【问题描述】:

在我的 Xamarin Forms 应用程序中,我有一个聊天页面,其中包含列出聊天项目的 ListView。

这是聊天页面视图模型:

public class IndexViewModel : BaseViewModel
{
    public ObservableCollection<Model.Chat> Items { get; set; }
    public Command LoadItemsCommand { get; set; }

    public IndexViewModel()
    {

        Items = new ObservableCollection<Model.Chat>();
        LoadItemsCommand = new Command( () => ReadTheList());

        MessagingCenter.Subscribe<RootPage, Model.Chat>(this, "NewMessage", (obj, item) =>
        {
            var chat = item as Model.Chat; // Inspecting this as a local variable during debugging looks fine
            // when an item is added like this the app freezes
            Items.Add(chat);
        });
    }

    void ReadTheList()
    {
        var items = repo.ChatList();
        Items.Clear();
        foreach (var item in items)
        {
            // when an item is added like this, all is fine
            Items.Add(item);
        }
    }

}

每当有新的聊天消息到达时,我都想向下滚动到最后一条消息(新添加的消息)。所以我在我的视图中添加了这个委托:

viewModel.Items.CollectionChanged += (sender, e) => 
{
    if (viewModel.Items.Count == 0) return;
    Debug.WriteLine("I can always see this when a chat item is added to the collection");
    chatList.ScrollTo(viewModel.Items.Last(), ScrollToPosition.End, false);  // this is where the freeze happens
};

当我从本地存储添加项目列表并且列表滚动到底部时,委托的最后一行工作正常,但是当通过 MessagingCenter 订阅添加新收到的聊天项目时,它会冻结我的应用程序。当有新消息到达并且页面打开并且我没有与页面上的任何内容进行交互时,这种情况总是会发生。

谁能帮我调试一下?

【问题讨论】:

  • 你试过把ScrollTo电话改成Device.BeginInvokeOnMainThread(() =&gt; chatList.ScrollTo(viewModel.Items.Last(), ScrollToPosition.End, false));吗?
  • @DiegoRafaelSouza 好建议!就是这样。您能否将其添加为答案,以便我标记它。

标签: listview xamarin.forms viewmodel


【解决方案1】:

在处理繁重的后台进程(例如处理列表搜索)时,请在单独的线程上执行以避免此类问题。

将您的 CllectionChanged 处理程序更改为:

viewModel.Items.CollectionChanged += (sender, e) => 
{
    if (viewModel.Items.Count == 0) return;
    Debug.WriteLine("I can always see this when a chat item is added to the collection");
    Device.BeginInvokeOnMainThread(() => 
        chatList.ScrollTo(viewModel.Items.Last(), ScrollToPosition.End, false));
};

【讨论】:

  • 其实我是在后台线程上运行的。问题是,我没有记住我在后台线程上,您的建议是回到主 UI 线程来进行 UI 更改。新消息调用由Task.Run(() =&gt; { MainPage.AddMessage(payload); });触发
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
相关资源
最近更新 更多