如何在Xamarin Forms中为标签添加垂直滚动条?

3

我有一段很长的文字,想要显示出来。我使用了一个标签。但是这个标签不能完全显示所有文字。我想让这个标签有一个垂直滚动条。

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

我尝试了不同的VerticalOptions来尝试调整这个标签的位置,但是没有任何效果。

如果对于标签来说这是不支持的,那么我可以使用其他控件吗?

3个回答

7

如果您想要垂直滚动,您必须使用ScrollView,在其中包含您的标签/网格,然后您就可以显示所有文本。

<ScrollView>

<Grid/>

</ScrollView/>

有没有示例?我是Xamarin的新手。 - Vivek Nuna
非常感谢,这真的很有帮助。 - Vivek Nuna

1
感谢Bruno Caceiro的提示。我已经根据他提供的提示解决了问题。
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;

0
如果您想在XAML中实现它,可以在<Scrollview>中使用Label。在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>

最好使用MVVM绑定或通过C#代码来指定长文本:

<ScrollView>
    <Label x:name="myLabel" Text="{Binding LongText} />
</ScrollView>

//OR in the code behind
myLabel.Text = "Your long text";

为了提高性能,最好使用MVVM绑定。

在XAML或C#代码后台(视图中)定义长字符串、列表或变量会带来很多性能开销和延迟问题。因此,始终优先使用MVVM模式以获得最佳的无延迟性能。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接