繁体   English   中英

如何给Xamarin Forms中的一个label添加垂直滚动?

[英]How to add vertical scroll to a label in Xamarin Forms?

我有一个大文本,我想显示它。 我为此使用 label。 但是这个label并没有显示全文。 我想要这个 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);

我为这个 label 尝试了不同的VerticalOptions ,但没有任何效果。

如果 label 不支持此功能。我可以使用其他控件吗?

如果要垂直滚动,则必须使用ScrollView,将标签/网格包裹在scrollview中,然后才能显示所有文本。

<ScrollView>

<Grid/>

</ScrollView/>

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

如果你想在Label<Scrollview>

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

在 XAML 或 C# 代码隐藏(在视图中)中定义长字符串、列表或变量有很多性能开销和滞后问题。 因此总是更喜欢使用 MVVM 模式来获得最佳的无滞后性能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM