スクロールビュー

サンプルを参照します。 サンプルを参照する

.NET マルチプラットフォーム アプリ UI (.NET MAUI) ScrollView は、コンテンツをスクロールできるビューです。 既定では、 ScrollView はコンテンツを垂直方向にスクロールします。 ScrollViewは子を 1 つだけ持つことができますが、他のレイアウトでもかまいません。

ScrollView には、次のプロパティが定義されています。

  • Contentは、 Viewの種類で、 ScrollViewに表示するコンテンツを表します。
  • ContentSizeは、 Size型のコンテンツのサイズを表します。 これは読み取り専用プロパティです。
  • HorizontalScrollBarVisibilityは、 ScrollBarVisibility型で、水平スクロール バーが表示されるタイミングを表します。
  • Orientationは ScrollOrientation型で、 ScrollViewのスクロール方向を表します。 このプロパティの既定値は Vertical です。
  • ScrollXは、 double型の現在の X スクロール位置を示します。 この読み取り専用プロパティの既定値は 0 です。
  • ScrollYは、 double型の現在の Y スクロール位置を示します。 この読み取り専用プロパティの既定値は 0 です。
  • VerticalScrollBarVisibilityは、 ScrollBarVisibility型で、垂直スクロール バーが表示されるタイミングを表します。

これらのプロパティは、BindableProperty プロパティを除き、Content オブジェクトによってサポートされます。つまり、データ バインディングのターゲットとしてスタイルを設定できます。

Content プロパティはContentProperty クラスのScrollViewであるため、XAML から明示的に設定する必要はありません。

Warnung

ScrollView オブジェクトは入れ子にしないでください。 さらに、 ScrollView オブジェクトは、 CollectionView、 ListView、 WebViewなど、スクロールを提供する他のコントロールと入れ子にしないでください。

ルートレイアウトとしてのScrollView

ScrollViewには 1 つの子しか含めず、他のレイアウトを使用できます。 そのため、 ScrollView がページ上のルート レイアウトになるのが一般的です。 子コンテンツをスクロールするには、 ScrollView コンテンツの高さと独自の高さの差を計算します。 その違いは、 ScrollView がコンテンツをスクロールできる量です。

StackLayoutは、多くの場合、ScrollViewの子になります。 このシナリオでは、 ScrollView により、 StackLayout は子の高さの合計と同じ高さになります。 その後、 ScrollView はコンテンツをスクロールできる量を決定できます。 StackLayoutの詳細については、「StackLayout」を参照してください。

注意事項

垂直方向の ScrollViewでは、 VerticalOptions プロパティを Start、 Center、または Endに設定しないでください。 それによって、ScrollView は必要な高さにだけ設定されることができ、その高さは場合によっては0になる可能性があります。 .NET MAUI はこの最終的な結果から保護されますが、発生したくないことを提案するコードは避けるのが最善です。

次の XAML の例には、ページ上のルート レイアウトとして ScrollView があります。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ScrollViewDemos"
             x:Class="ScrollViewDemos.Views.XAML.ColorListPage"
             Title="ScrollView demo">
    <ScrollView Margin="20">
        <StackLayout BindableLayout.ItemsSource="{x:Static local:NamedColor.All}">
            <BindableLayout.ItemTemplate>
                <DataTemplate x:DataType="local:NamedColor">
                    <StackLayout Orientation="Horizontal">
                        <BoxView Color="{Binding Color}"
                                 HeightRequest="32"
                                 WidthRequest="32"
                                 VerticalOptions="Center" />
                        <Label Text="{Binding FriendlyName}"
                               FontSize="24"
                               VerticalOptions="Center" />
                    </StackLayout>
                </DataTemplate>
            </BindableLayout.ItemTemplate>
        </StackLayout>
    </ScrollView>
</ContentPage>

この例では、ScrollViewのコンテンツは、バインド可能なレイアウトを使用して .NET MAUI で定義されたStackLayout フィールドを表示するColorsに設定されています。 既定では、 ScrollView は垂直方向にスクロールされ、より多くのコンテンツが表示されます。

ルート ScrollView レイアウトのスクリーンショット。

同等の C# コードは次のとおりです。

public class ColorListPage : ContentPage
{
    public ColorListPage()
    {
        DataTemplate dataTemplate = new DataTemplate(() =>
        {
            BoxView boxView = new BoxView
            {
                HeightRequest = 32,
                WidthRequest = 32,
                VerticalOptions = LayoutOptions.Center
            };
            boxView.SetBinding(BoxView.ColorProperty, static (NamedColor nc) => nc.Color);

            Label label = new Label
            {
                FontSize = 24,
                VerticalOptions = LayoutOptions.Center
            };
            label.SetBinding(Label.TextProperty, static (NamedColor nc) => nc.FriendlyName);

            StackLayout horizontalStackLayout = new StackLayout
            {
                Orientation = StackOrientation.Horizontal
            };
            horizontalStackLayout.Add(boxView);
            horizontalStackLayout.Add(label);

            return horizontalStackLayout;
        });

        StackLayout stackLayout = new StackLayout();
        BindableLayout.SetItemsSource(stackLayout, NamedColor.All);
        BindableLayout.SetItemTemplate(stackLayout, dataTemplate);

        ScrollView scrollView = new ScrollView
        {
            Margin = new Thickness(20),
            Content = stackLayout
        };

        Title = "ScrollView demo";
        Content = scrollView;
    }
}

バインド可能なレイアウトの詳細については、「 BindableLayout」を参照してください。

子レイアウトとしての ScrollView

ScrollViewは、別の親レイアウトへの子レイアウトにすることができます。

ScrollViewは、多くの場合、Gridの子になります。 ScrollViewでは、コンテンツの高さとそれ自体の高さの差を計算するために特定の高さが必要です。その差は、ScrollViewがコンテンツをスクロールできる量です。 ScrollViewがGridの子である場合、特定の高さは受け取りません。 Gridでは、ScrollViewをできるだけ短くする必要があります。これは、ScrollViewコンテンツの高さまたはゼロのいずれかです。 このシナリオを処理するには、RowDefinitionを含むGrid行のScrollViewを*に設定する必要があります。 これにより、 Grid は他の子が必要としていない余分なスペースをすべて ScrollView に与え、 ScrollView は特定の高さを持ちます。

次の XAML の例では、ScrollViewへの子レイアウトとしてGridがあります。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ScrollViewDemos.Views.XAML.BlackCatPage"
             Title="ScrollView as a child layout demo">
    <Grid Margin="20"
          RowDefinitions="Auto,*,Auto">
        <Label Text="THE BLACK CAT by Edgar Allan Poe"
               FontSize="14"
               FontAttributes="Bold"
               HorizontalOptions="Center" />
        <ScrollView x:Name="scrollView"
                    Grid.Row="1"
                    VerticalOptions="Fill"
                    Scrolled="OnScrollViewScrolled">
            <StackLayout>
                <Label Text="FOR the most wild, yet most homely narrative which I am about to pen, I neither expect nor solicit belief. Mad indeed would I be to expect it, in a case where my very senses reject their own evidence. Yet, mad am I not -- and very surely do I not dream. But to-morrow I die, and to-day I would unburthen my soul. My immediate purpose is to place before the world, plainly, succinctly, and without comment, a series of mere household events. In their consequences, these events have terrified -- have tortured -- have destroyed me. Yet I will not attempt to expound them. To me, they have presented little but Horror -- to many they will seem less terrible than barroques. Hereafter, perhaps, some intellect may be found which will reduce my phantasm to the common-place -- some intellect more calm, more logical, and far less excitable than my own, which will perceive, in the circumstances I detail with awe, nothing more than an ordinary succession of very natural causes and effects." />
                <!-- More Label objects go here -->
            </StackLayout>
        </ScrollView>
        <Button Grid.Row="2"
                Text="Scroll to end"
                Clicked="OnButtonClicked" />
    </Grid>
</ContentPage>

この例では、ルート レイアウトは、子としてGrid、Label、およびScrollViewを持つButtonです。 ScrollViewにはコンテンツとしてStackLayoutがあり、StackLayoutには複数のLabel オブジェクトが含まれています。 この配置により、最初の Label は常に画面に表示されますが、他の Label オブジェクトによって表示されるテキストはスクロールできます。

ScrollView の子レイアウトのスクリーンショット。

同等の C# コードは次のとおりです。

public class BlackCatPage : ContentPage
{
    public BlackCatPage()
    {
        Label titleLabel = new Label
        {
            Text = "THE BLACK CAT by Edgar Allan Poe",
            // More properties set here to define the Label appearance
        };

        StackLayout stackLayout = new StackLayout();
        stackLayout.Add(new Label { Text = "FOR the most wild, yet most homely narrative which I am about to pen, I neither expect nor solicit belief. Mad indeed would I be to expect it, in a case where my very senses reject their own evidence. Yet, mad am I not -- and very surely do I not dream. But to-morrow I die, and to-day I would unburthen my soul. My immediate purpose is to place before the world, plainly, succinctly, and without comment, a series of mere household events. In their consequences, these events have terrified -- have tortured -- have destroyed me. Yet I will not attempt to expound them. To me, they have presented little but Horror -- to many they will seem less terrible than barroques. Hereafter, perhaps, some intellect may be found which will reduce my phantasm to the common-place -- some intellect more calm, more logical, and far less excitable than my own, which will perceive, in the circumstances I detail with awe, nothing more than an ordinary succession of very natural causes and effects." });
        // More Label objects go here

        ScrollView scrollView = new ScrollView();
        scrollView.Content = stackLayout;
        // ...

        Title = "ScrollView as a child layout demo";
        Grid grid = new Grid
        {
            Margin = new Thickness(20),
            RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) },
                new RowDefinition { Height = new GridLength(1, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(0, GridUnitType.Auto) }
            }
        };
        grid.Add(titleLabel);
        grid.Add(scrollView, 0, 1);
        grid.Add(button, 0, 2);

        Content = grid;
    }
}

オリエンテーション

ScrollViewには、Orientationのスクロール方向を表す ScrollView プロパティがあります。 このプロパティは、次のメンバーを定義する ScrollOrientation型です。

  • Vertical は、 ScrollView が垂直方向にスクロールすることを示します。 このメンバーは、 Orientation プロパティの既定値です。
  • Horizontal は、 ScrollView が水平方向にスクロールすることを示します。
  • Both は、 ScrollView が水平方向と垂直方向にスクロールすることを示します。
  • Neither は、 ScrollView がスクロールしないことを示します。

ヒント

Orientation プロパティを Neither に設定すると、スクロールを無効にできます。

スクロールを検出する

ScrollView は、スクロールが発生したことを示すために発生する Scrolled イベントを定義します。 ScrolledEventArgs イベントに付随するScrolled オブジェクトには、ScrollXプロパティとScrollYプロパティがあり、どちらもdouble型です。

Important

ScrolledEventArgs.ScrollXプロパティとScrolledEventArgs.ScrollY プロパティは、ScrollViewの先頭までスクロールしたときに発生するバウンス効果により、負の値を持つことができます。

次の XAML の例は、ScrollView に対して Scrolled イベント ハンドラーを設定する方法を示しています。

<ScrollView Scrolled="OnScrollViewScrolled">
    ...
</ScrollView>

同等の C# コードは次のとおりです。

ScrollView scrollView = new ScrollView();
scrollView.Scrolled += OnScrollViewScrolled;

この例では、OnScrollViewScrolled イベントが発生したときに、Scrolled イベント ハンドラーが実行されます。

void OnScrollViewScrolled(object sender, ScrolledEventArgs e)
{
    Console.WriteLine($"ScrollX: {e.ScrollX}, ScrollY: {e.ScrollY}");
}

この例では、 OnScrollViewScrolled イベント ハンドラーは、イベントに付随する ScrolledEventArgs オブジェクトの値を出力します。

注

Scrolled イベントは、ユーザーが開始したスクロールとプログラムによるスクロールに対して発生します。

プログラムでスクロールする

ScrollViewは、ScrollToAsyncを非同期的にスクロールする 2 つのScrollView メソッドを定義します。 オーバーロードの 1 つは ScrollView内の指定した位置までスクロールし、もう 1 つは指定した要素をビューにスクロールします。 どちらのオーバーロードにも、スクロールをアニメーション化するかどうかを示すために使用できる追加の引数があります。

Important

ScrollToAsyncプロパティが ScrollView.Orientation に設定されている場合、Neither メソッドはスクロールされません。

位置をスクロールして表示する

ScrollView内の位置は、ScrollToAsyncdouble引数とx引数を受け取るy メソッドを使用してスクロールできます。 ScrollViewという名前の垂直scrollView オブジェクトを指定すると、次の例は、ScrollViewの上部からデバイスに依存しない 150 単位までスクロールする方法を示しています。

await scrollView.ScrollToAsync(0, 150, true);

ScrollToAsyncの 3 番目の引数は animated 引数です。これは、プログラムによってScrollViewをスクロールするときにスクロール アニメーションを表示するかどうかを決定します。

要素をスクロールして表示する

ScrollView内の要素は、ScrollToAsync引数とElement引数を受け取るScrollToPosition メソッドを使用してビューにスクロールできます。 ScrollViewという名前の垂直scrollViewと、Labelという名前のlabelがある場合、次の例は要素をスクロールして表示する方法を示しています。

await scrollView.ScrollToAsync(label, ScrollToPosition.End, true);

ScrollToAsyncの 3 番目の引数は animated 引数です。これは、プログラムによってScrollViewをスクロールするときにスクロール アニメーションを表示するかどうかを決定します。

要素をビューにスクロールする場合、スクロールが完了した後の要素の正確な位置は、position メソッドの 2 番目の引数 (ScrollToAsync) で設定できます。 この引数は、 ScrollToPosition 列挙メンバーを受け入れます。

  • MakeVisible は、要素が ScrollViewに表示されるまでスクロールする必要があることを示します。
  • Start は、要素を ScrollViewの先頭までスクロールする必要があることを示します。
  • Center は、要素を ScrollViewの中心までスクロールする必要があることを示します。
  • End は、要素を ScrollViewの末尾までスクロールする必要があることを示します。

スクロール バーの表示

ScrollView は、バインド可能なプロパティによってサポートされる HorizontalScrollBarVisibility プロパティと VerticalScrollBarVisibility プロパティを定義します。 これらのプロパティは、水平スクロール バーと垂直スクロール バーのどちらを表示するかを表す ScrollBarVisibility 列挙値を取得または設定します。 ScrollBarVisibility 列挙型には、次のメンバーが定義されています。

  • Default は、プラットフォームの既定のスクロール バーの動作を示し、 HorizontalScrollBarVisibility プロパティと VerticalScrollBarVisibility プロパティの既定値です。
  • Always は、コンテンツがビューに収まる場合でも、スクロール バーが表示されることを示します。
  • Never は、コンテンツがビューに収まらない場合でも、スクロール バーが表示されないことを示します。