首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >谁有聊天用的Listview渲染器?

谁有聊天用的Listview渲染器?
EN

Stack Overflow用户
提问于 2019-05-22 20:27:01
回答 2查看 159关注 0票数 -4

我需要一个像whatsapp聊天的ListView渲染器。

当新消息到来时,它会自动向下滚动。

如果有样品,请告诉我。

谢谢

EN

回答 2

Stack Overflow用户

发布于 2019-05-23 02:05:02

你不需要一个自定义的渲染器,你只需要使用一个ListView并添加一些逻辑来为你做滚动。

View.xaml文件:

代码语言:javascript
复制
<!-- Previous Implementation -->

        <ListView x:Name="MessagesListView"
              Grid.Row="0"
              BackgroundColor="Transparent"
              HasUnevenRows="True"
              ItemTemplate="{StaticResource MessageTemplateSelector}"
              ItemsSource="{Binding Messages}"
              SelectionMode="None"
              SeparatorVisibility="None" />

<!-- Remaining Implementation -->

x:Name属性是重要的部分,您将在后面的代码中使用该名称。

现在是View.xaml.cs文件:

代码语言:javascript
复制
// Previous Implmentation

    /// <summary>
    /// Override of OnAppearing method. Fires as page is appearing.
    /// Good place to set up event handlers.
    /// </summary>
    protected override void OnAppearing()
    {
        base.OnAppearing();

        ((INotifyCollectionChanged)MessagesListView.ItemsSource).CollectionChanged += OnListViewCollectionChanged;
    }

    /// <summary>
    /// Override of OnDisappearing method. Fires as page is disappearing.
    /// Good place to tear down event handlers.
    /// </summary>
    protected override void OnDisappearing()
    {
        base.OnDisappearing();

        ((INotifyCollectionChanged)MessagesListView.ItemsSource).CollectionChanged -= OnListViewCollectionChanged;
    }

    /// <summary>
    /// Scrolls a the messages listview to the last item whenever
    /// a new message is added to the collection.
    /// </summary>
    private void OnListViewCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        var myList = ((IEnumerable<Message>)MessagesListView.ItemsSource).ToList();

        // Must be ran on main thread or Android chokes.
        Device.BeginInvokeOnMainThread(async () =>
        {
            // For some reason Android requires a small delay or the scroll never happens.
            await Task.Delay(50);
            MessagesListView.ScrollTo(myList.Last(), ScrollToPosition.End, false);
        });
    }

// Remaining Implementation

基本上,只要ListView的ItemSource发生变化,就会触发一个事件。在这种情况下,您将滚动到列表的末尾。

票数 1
EN

Stack Overflow用户

发布于 2019-05-22 23:50:48

你不需要一个自定义渲染器来聊天,因为一个简单的ListView就足够了。

基本上,您将把ItemsSource属性绑定到一个ObservableCollection,这样当添加新消息时,它将自动出现在列表视图中。

此外,如果您认为用户不需要/必须立即查看大量历史聊天消息,则可能需要使用无限滚动技术,例如https://www.youtube.com/watch?v=DG5Asglf0vU

要滚动到最后一条消息:

代码语言:javascript
复制
Device.BeginInvokeOnMainThread (() => {
           Listviewname.scrollto(items[count-1], scrolltoposition.end, false)
       });
 });
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56256802

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档