如何在Xamarin.forms中自动向下滚动ListView(MVVM设计模式)

Mat*_*ano 1 listview mvvm xamarin.forms

我开发了一个与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>
Run Code Online (Sandbox Code Playgroud)

由于我的设计模式,我不能使用ScrollTo方法(我是对的吗?)并且xaml中没有ScrollTo属性.

那么这个问题的解决方案是什么?

谢谢!

Ger*_*uis 7

解决此问题的一种方法是使用MessagingCenter.

从您的PageModel发送信号,即

MessagingCenter.Send<object> (this, "MessageReceived");
Run Code Online (Sandbox Code Playgroud)

然后在您的Page的代码隐藏中,您可以订阅它并向下滚动或执行任何操作.

MessagingCenter.Subscribe<object> (this, "MessageReceived", (sender) => {
    MainScreenMessagesListView.ScrollTo(..., ScrollToPosition.End, true);
});
Run Code Online (Sandbox Code Playgroud)

您必须将最后一项确定为您的对象,而不是点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);
});
Run Code Online (Sandbox Code Playgroud)