How to add vertical scroll to a label in Xamarin Forms?

Viewed 4204

I have a large text, I want to display it. I am using a label for this. But this label does not show full text. I want a vertical scroll for this label.

Grid mainGrid = new Grid
{
    HeightRequest = 40,
    BackgroundColor = Color.White,
    Padding = 20,
    RowDefinitions =
    {

        new RowDefinition { Height = new GridLength(25, GridUnitType.Star) },//0 Title
        new RowDefinition { Height = new GridLength(5, GridUnitType.Star) },//1 Line
        new RowDefinition { Height = new GridLength(50, GridUnitType.Star) },//2 This is for MessageLabel
        new RowDefinition { Height = new GridLength(20, GridUnitType.Star) },//3 OK-Cancel
    }
};    

MessageLabel = new Label
{
    FontAttributes = FontAttributes.None,
    FontSize = 18,
    HorizontalTextAlignment = TextAlignment.Start,
    VerticalTextAlignment = TextAlignment.Center,
    HorizontalOptions = LayoutOptions.StartAndExpand,
    TextColor = Color.Black,
};

mainGrid.Children.Add(MessageLabel, 0, 2);

I have tried different VerticalOptions for this label, But nothing is working.

If this is not supported for a label. Can I use some other control?

3 Answers

If you want vertical scroll, you must use a ScrollView, wrap your label / grid within a scrollview, then you can display all the text.

<ScrollView>

<Grid/>

</ScrollView/>

Thank you Bruno Caceiro for the hint. I have solved the problem with the hint he has provided.

MessageLabel = new Label
{
    FontAttributes = FontAttributes.None,
    FontSize = 18,
    HorizontalTextAlignment = TextAlignment.Start,
    VerticalTextAlignment = TextAlignment.Center,
    HorizontalOptions = LayoutOptions.StartAndExpand,
    TextColor = Color.Black
};

ScrollView scroll = new ScrollView()
{
    Orientation = ScrollOrientation.Vertical
};

scroll.Content = MessageLabel;

If you want to do it in XAML, Label in <Scrollview>

It's simple in XAML:

<ScrollView>
    <Label Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam imperdiet odio vitae nulla ornare gravida. Quisque dictum nulla felis, feugiat rutrum odio ultricies id. Sed rutrum, lacus ut feugiat congue, quam libero porta dolor, quis ultrices tortor risus eu est. Praesent finibus tincidunt magna, eu lacinia nibh consequat non." />
</ScrollView>

It would be ideal to specify Long Text using MVVM Binding or through C# Code Behind:

<ScrollView>
    <Label x:name="myLabel" Text="{Binding LongText} />
</ScrollView>
//OR in the code behind
myLabel.Text = "Your long text";

For performance, it is best using MVVM Binding.

Defining long strings, lists or variables in XAML or C# Code Behind (In the View) has a lot of performance overhead and lagging issues. Hence always prefer using MVVM pattern to get best lagfree performance.

Related