Xamarin在运行时计算堆栈布局高度

ogsagwnx  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(160)

I am trying to create a dynamic view, where I get the data from the backend and create views for it on my Xamarin App.
In the XAML view I have a simple stack layout

<StackLayout x:Name="Container">
</StackLayout>

and I am creating views as soon as the date is retrieved as so

Label label = new Label();
label.Text= Text;
label.LineHeight = 1.1;
Container.Children.Add(CreateLabel(label));

The problem is the view doesn't expand to fit all the elements added
calculating the height and setting it as the HeightRequest for stack layout didn't work
any idea or suggestion would be nice.

tzxcd3kk

tzxcd3kk1#

我通过编写MainPage.xaml.cs文件为您做了一个演示。

public partial class MainPage : ContentPage
    {
        String Text1 = "This is a text. This is a text.This is a text.This is a text.";
        Double LineHeight1 = 1.78;
        public MainPage()
        {
            InitializeComponent();
            var layout = new StackLayout {  };
            var label = new Label { Text = Text1, TextColor = Color.Black, FontSize = 20, LineHeight = LineHeight1, BackgroundColor = Color.Red, LineBreakMode = LineBreakMode.WordWrap };
            layout.Children.Add(label);
            this.Content = layout;

        }
    }

您可以看到我创建了一个StackLayout和一个标签,并将布局绑定到内容。它运行良好,您可以尝试一下。

相关问题