xamarin - 如何将 TableView 滚动到顶部

标签 xamarin xamarin.forms

这看起来应该很简单,但没有 ScrollTo TableView 上的方法与 ListView 一样。

如何将 TableView 滚动到顶部?

最佳答案

Forms 的 TableView 并非设计为像 ScrollView 一样进行控制,即使它们是使用可滚动容器 native 实现的。

虽然由于效果开销,自定义渲染器将是我显示滚动功能的首选,但快速 PlatformEffect黑客使用 MessagingCenter将用作演示:

在 Android 上,Forms 的 TableView 使用 Android.Widget.ListView作为它的顶级容器,所以 ListView.SmoothScrollToPosition可以使用。

Android PlatformEffect(使用 MessagingCenter)

public class ScrollTopEffect : PlatformEffect
{
    void ScrollToTop(TableView obj)
    {
        (Control as AListView).SmoothScrollToPosition(0);
    }

    protected override void OnAttached()
    {
        if (Element is TableView)
            MessagingCenter.Subscribe<TableView>(Element as TableView, "ScrollTop", ScrollToTop);
        else
            throw new Exception("ScrollTopEffect must be used on a TableView (Android.Widget.ListView)");
    }

    protected override void OnDetached()
    {
        MessagingCenter.Unsubscribe<TableView>(Element as TableView, "ScrollTop");
    }
}

Xamarin.Forms 用法:
MessagingCenter.Send<TableView>(tableView, "ScrollTop");

注意:实例tableView var 必须是您希望滚动到顶部的那个。

在 iOS 上,Forms 使用 UITableView作为 TableView 的顶部容器,因此您可以使用 `UITableView.SetContentOffset` 滚动到顶部。

iOS PlatformEffect(使用 MessagingCenter)
public class ScrollTopEffect : PlatformEffect
{
    void ScrollToTop(TableView obj)
    {
        (Control as UITableView).SetContentOffset(CGPoint.Empty, true);
    }

    protected override void OnAttached()
    {
        if (Element is TableView)
            MessagingCenter.Subscribe<TableView>(Element as TableView, "ScrollTop", ScrollToTop);
        else
            throw new Exception("ScrollTopEffect must be used on a TableView (UIkit.UITableView)");
    }

    protected override void OnDetached()
    {
        MessagingCenter.Unsubscribe<TableView>(Element as TableView, "ScrollTop");
    }
} 

关于xamarin - 如何将 TableView 滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49786486/

相关文章:

c# - 应用程序在后台时不显示通知

android - xamarin android webview : video not playing on device

c# - 嵌入 Xamarin Forms 或 native 嵌入

Xamarin Android 应用程序消耗异常大量的电池。为什么?

c# - Xamarin 表单按钮 OnClick

c# - MvvmCross 在 .NET Standard 项目中使用的实际 SQLite 插件

c# - 我可以将列表移到后面吗?

c# - 无法确定 Xamarin Forms 应用程序是在模拟器中运行还是在设备上运行

c# - ContentView Xamarin 表单

c# - 删除 Xamarin.Forms 中 ListView GroupHeaders 之间不需要的间距