在Xamarin.Forms ScrollView中水平滚动

时间:2014-06-24 14:46:41

标签: xamarin.forms

我正在使用Xamarin.Forms并创建了一个包含水平StackLayout的ScrollView。我希望能够水平滚动,所以我设置:

Orientation  = ScrollOrientation.Horizontal;

但我不能横向滚动。 StackLayout的内容比屏幕宽,我看到内容被剪裁在边缘。

如何使用Xamarin.Forms实现水平滚动?

3 个答案:

答案 0 :(得分:19)

这就是我开始工作的方式

      var scrollView = ScrollView
        {
            HorizontalOptions = LayoutOptions.Fill,
            Orientation = ScrollOrientation.Horizontal,

            Content = new StackLayout{
               Orientation = StackOrientation.Horizontal,
               Children = {}
            }
        };

答案 1 :(得分:1)

这个nuget包将起作用:

https://github.com/SuavePirate/DynamicStackLayout

属性Words是字符串列表:

    <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>

我希望它有所帮助:)

答案 2 :(得分:0)

如果您在Visual Studio 2013中使用Xamarin应用程序中的模板,则Xamarin.Forms的版本有点过时,不支持滚动。为了解决这个问题,只需要nuget&#39; update-package&#39;和这段代码

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, 
        };
    }
}

代码在android上运行正常。

对于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;
            }
        }
    }
}