如何将ListView设置为开始在Xamarin表单中显示最后一个项目? [英] How to set ListView to Start showing the last Item instead in Xamarin Forms?

查看:157
本文介绍了如何将ListView设置为开始在Xamarin表单中显示最后一个项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由ListView处理的项目列表.默认情况下,ListView从头到尾显示(滚动).

I have a list of Items being handled by the ListView. By default, the ListView shows the from start to bottom (scrolling).

如何将ListView设置为从底部开始?

How do I set the ListView to start at the bottom instead?

用法: 聊天消息视图-我需要在其中显示聊天的最后一条消息并滚动到该消息.

Usage: Chat Messages View - Wherein I need to show the last message of the chat and scroll to that.

推荐答案

您可以在ListView中使用ScrollTo滚动到您设置的任何位置.您需要覆盖OnAppearing方法.这是滚动到ListView ViewModel.Messages:

You can use ScrollTo in a ListView to scroll to a any position you set. You need to overwrite the OnAppearing method. This is an example for scrolling to the end of the ListView ViewModel.Messages:

protected override void OnAppearing()
    {
        base.OnAppearing();

        ViewModel.RefreshScrollDown = () => {
            if (ViewModel.Messages.Count > 0) {
                Device.BeginInvokeOnMainThread (() => {

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

然后,每次需要向下滚动时,只需调用RefreshScrollDown(即System.Action),例如当您收到新消息或加载聊天时.

Then just call RefreshScrollDown (which is System.Action) every time you need to scroll down, e.g. when you receive a new message or when you load the chats.

ViewModel中的RefreshScrollDown:

public System.Action RefreshScrollDown;

您可以像下面这样在代码中获取ViewModel:

private MessagePhonePageViewModel ViewModel {
    get { return BindingContext as MessagePhonePageViewModel;}
}


注意:使用固定的ListView高度时存在错误.更改HeightRequest时, ScrollTo 仍使用列表的原始高度来计算滚动到的位置.更改HeightRequest中的值时,原始高度不会更新.要解决此问题:


NOTE: There is a bug when using a fixed ListView height. When changing the HeightRequest, ScrollTo still uses the original height of the list to calculate where it scrolls to. The original height is not updated when you change the value in HeightRequest. To fix this issue:

 protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);
            if (e.PropertyName == Xamarin.Forms.ListView.HeightRequestProperty.PropertyName)
            {
                Control.LayoutParameters.Height =(int)(sender as Xamarin.Forms.ListView).HeightRequest;
                Control.RequestLayout();

            }
        }  

这篇关于如何将ListView设置为开始在Xamarin表单中显示最后一个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆