我使用Xamarin.Forms(MVVM设计模式)开发了一个聊天应用程序。发送消息后,我需要自动向下滚动ListView(聊天消息列表)。
我的看法:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
...>
<ContentPage.Content>
<StackLayout Style="{StaticResource MainLayoutStyle}">
...
<Frame
HorizontalOptions="FillAndExpand"
VerticalOptions="FillAndExpand"
CornerRadius="5"
BackgroundColor="White"
Padding="5">
<ScrollView>
<StackLayout>
<ListView
x:Name="MainScreenMessagesListView"
ItemTemplate="{StaticResource MessageTemplateSelector}"
HasUnevenRows="True"
BackgroundColor="#e5ddd5"
ItemsSource="{Binding Messages}">
</ListView>
</StackLayout>
</ScrollView>
</Frame>
...
</StackLayout>
</ContentPage.Content>
由于我的设计模式,我不能使用ScrollTo方法(对吗?),并且xaml中没有ScrollTo属性。
那么该问题的解决方案是什么?
谢谢!
解决此问题的一种方法是使用MessagingCenter。
从您的PageModel发送信号,即
MessagingCenter.Send<object> (this, "MessageReceived");
然后,在页面的代码隐藏中,您可以订阅它并向下滚动或执行任何操作。
MessagingCenter.Subscribe<object> (this, "MessageReceived", (sender) => {
MainScreenMessagesListView.ScrollTo(..., ScrollToPosition.End, true);
});
您必须将最后一项确定为对象中的对象,而不是点ListView
。您可以通过两种方式执行此操作,或者通过投射的ItemsSource
属性在页面中确定它ListView
。但是,最好将其作为参数与MessagingCenter调用一起提供。
在您的PageModel中,您可以将其更改为: MessagingCenter.Send<object, object> (this, "MessageReceived", lastReceivedMessage);
并像这样检索值:
MessagingCenter.Subscribe<object, object> (this, "MessageReceived", (sender, arg) => {
MainScreenMessagesListView.ScrollTo(arg, ScrollToPosition.End, true);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句