如何显示Stacklayout子项的内容而不是对象的名称?

问题描述

我正在尝试从代码动态创建StackLayout。参考文档以及关于StackOverflow的几个问题,到目前为止,这就是我所要解决的问题,

XAML视图:

 <StackLayout  BindableLayout.ItemsSource="{Binding Items.Children}"/>

viewmodel:

public StackLayout Items { get; } = new StackLayout { 
        Margin = new Thickness(20),Children =
        {
            new Label { Text = "Primary colors" },new BoxView { Color = Color.Red },new BoxView { Color = Color.Yellow },new BoxView { Color = Color.Blue },new Label { Text = "Secondary colors" },new BoxView { Color = Color.Green },new BoxView { Color = Color.Orange },new BoxView { Color = Color.Purple }
        }
    };

VM中的代码只是一个示例,我在那里可能有各种对象。但是现在,这就是我得到的结果。

enter image description here

如何显示实际内容,例如文本,标签的颜色和方框视图?

解决方法

您只需要将您动态创建的StackLayout添加到页面Content

例如:

public partial class YourPage: ContentPage
{

   public YourPage()
    {
        YourVM vm = new YourVM();
        Content = vm.Items;
    }

}

您的 ViewModel

public class YourVM
{
    public StackLayout Items { get; } = new StackLayout { 
    Margin = new Thickness(20),Children =
    {
        new Label { Text = "Primary colors" },new BoxView { Color = Color.Red },new BoxView { Color = Color.Yellow },new BoxView { Color = Color.Blue },new Label { Text = "Secondary colors" },new BoxView { Color = Color.Green },new BoxView { Color = Color.Orange },new BoxView { Color = Color.Purple }
    }
};
}