Search code examples
c#macosscrollviewscrollbarmaui

ScrollView does not scroll unless window is resized in .NET MAUI


I am new to .NET MAUI.

I have a scroll view and inside the scroll view I have a Vertical Stack Layout with 2 items, a label and a button.

<ScrollView>
    <VerticalStackLayout
        x:Name="Stack"
        Spacing="25"
        Padding="30,0"
        VerticalOptions="Center">

        <Label
            Text="Hello, World!"
            SemanticProperties.HeadingLevel="Level1"
            FontSize="32"
            HorizontalOptions="Center" />

        <Button
            x:Name="ThirdButton"
            Text="Create Label"
            Clicked="OnCreateClicked"
            HorizontalOptions="Start" />

    </VerticalStackLayout>
</ScrollView>

When the button is clicked, I add labels to the stack dynamically.

private void OnCreateClicked(object sender, EventArgs e)
{
    Label label = new Label { Text = "This is a new label" };
    Stack.Add(label);
}

What I expect to happen is when the content size of the StackLayout is bigger than the size of the ScrollView, the scrollbar appear and I can scroll the view.

However it is not happening. I need to resize the window at least a few pixels in order to get the scrollbar appear and able to scroll the view.

Using:

macOS 13.1 Visual Studio 2022 for Mac .NET 7

Target platform: Mac(MacCatalyst)

I have tried with no success:

  1. setting the HorizontalScrollbarVisibility to "Always"
  2. setting the HorizontalOption to "FillandExpand"

I was also searching the documentation for any other solution but did not find any.

I would appreciator any help.

Thank you.


Solution

  • You could try the following code:

    In .xaml, name the Scrollview

    <ScrollView x:Name="myscroll">
    

    Then in .cs file, when add the label:

    private void OnCreateClicked(object sender, EventArgs e)
    {
        Label label = new Label { Text = "This is a new label" };
        Stack.Add(label);
        // Signals that the measure value of this View must be recomputed 
        (myscroll as IView).InvalidateMeasure();
    }
    

    Hope it works for you.