[英]How to set ListView to Start showing the last Item instead in Xamarin Forms?
I have a list of Items being handled by the ListView. 我有一个由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? 如何将ListView设置为从底部开始?
Usage: Chat Messages View - Wherein I need to show the last message of the chat and scroll to that. 用法:聊天消息视图 - 其中我需要显示聊天的最后一条消息并滚动到该消息。
You can use ScrollTo
in a ListView
to scroll to a any position you set. 您可以在
ListView
使用ScrollTo
滚动到您设置的任何位置。 You need to overwrite the OnAppearing
method. 您需要覆盖
OnAppearing
方法。 This is an example for scrolling to the end of the ListView
ViewModel.Messages: 这是滚动到
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);
});
}
};
}
Then just call RefreshScrollDown
(which is System.Action
) every time you need to scroll down, eg when you receive a new message or when you load the chats. 然后每次需要向下滚动时调用
RefreshScrollDown
(即System.Action
),例如,当您收到新消息或加载聊天时。
RefreshScrollDown in ViewModel: ViewModel中的RefreshScrollDown:
public System.Action RefreshScrollDown;
You can get your ViewModel in code behind like this: 您可以在后面的代码中获取ViewModel,如下所示:
private MessagePhonePageViewModel ViewModel {
get { return BindingContext as MessagePhonePageViewModel;}
}
NOTE: There is a bug when using a fixed ListView
height. 注意:使用固定的
ListView
高度时有一个错误。 When changing the HeightRequest
, ScrollTo still uses the original height of the list to calculate where it scrolls to. 更改
HeightRequest
, ScrollTo仍然使用列表的原始高度来计算滚动到的位置。 The original height is not updated when you change the value in HeightRequest
. 更改
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.