我正在使用Xamarin.Forms并创建了一个ScrollView,其中包含一个水平的StackLayout。我希望能够水平滚动,因此我设置了:
Orientation = ScrollOrientation.Horizontal;
但是我无法横向滚动。 StackLayout 的内容比屏幕宽,我看到内容在边缘被裁剪。
如何在 Xamarin.Forms 中实现横向滚动?
我正在使用Xamarin.Forms并创建了一个ScrollView,其中包含一个水平的StackLayout。我希望能够水平滚动,因此我设置了:
Orientation = ScrollOrientation.Horizontal;
但是我无法横向滚动。 StackLayout 的内容比屏幕宽,我看到内容在边缘被裁剪。
如何在 Xamarin.Forms 中实现横向滚动?
这是我让它正常工作的方法
var scrollView = ScrollView
{
HorizontalOptions = LayoutOptions.Fill,
Orientation = ScrollOrientation.Horizontal,
Content = new StackLayout{
Orientation = StackOrientation.Horizontal,
Children = {}
}
};
<ScrollView Orientation="Horizontal" HorizontalOptions="FillAndExpand">
<dynamicStackLayout:DynamicStackLayout ItemsSource="{Binding Words}" HorizontalOptions="Fill" Orientation="Horizontal" Padding="10, -0, 50, 10">
<dynamicStackLayout:DynamicStackLayout.ItemTemplate>
<DataTemplate>
<StackLayout BackgroundColor="Gray" WidthRequest="80" HeightRequest="80">
<Label Text="{Binding .}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" VerticalTextAlignment="Center" HorizontalTextAlignment="Center" />
</StackLayout>
</DataTemplate>
</dynamicStackLayout:DynamicStackLayout.ItemTemplate>
</dynamicStackLayout:DynamicStackLayout>
</ScrollView>
public class MainPage : ContentPage
{
public MainPage()
{
Label label = new Label {
Text = "This is a very long label which I expect to scroll horizontally because it's in a ScrollView.",
Font = Font.SystemFontOfSize(24),
};
this.Content = new ScrollView {
Content = label,
Orientation = ScrollOrientation.Horizontal,
};
}
}
这段代码在安卓上可以正常运行。
对于iOS,代码也能按预期工作。
不幸的是,目前在WP8上存在一个错误,解决方法是添加自定义渲染器。
using System.Windows.Controls;
using App2.WinPhone;
using Xamarin.Forms;
using Xamarin.Forms.Platform.WinPhone;
[assembly: ExportRenderer(typeof(ScrollView), typeof(FixedSVRenderer))]
namespace App2.WinPhone
{
public sealed class FixedSVRenderer : ScrollViewRenderer
{
protected override void OnModelSet()
{
base.OnModelSet();
if (Model.Orientation == ScrollOrientation.Horizontal)
{
// Enable horiz-scrolling
Control.HorizontalScrollBarVisibility = ScrollBarVisibility.Auto;
}
}
}
}