【问题标题】:How to display content of Stacklayout children instead of name of the objects?如何显示 Stacklayout 子项的内容而不是对象的名称?
【发布时间】:2021-02-16 08:55:25
【问题描述】:

我正在尝试从代码动态创建 StackLayout。参考 StackOverflow 上的文档和一些问题,这就是我目前所拥有的,

XAML 视图:

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

视图模型:

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 中的代码只是一个示例,我将在其中包含各种对象。但现在,这就是我得到的结果。

如何显示文本、标签颜色和框视图等实际内容?

【问题讨论】:

  • 如果你要手动构建 StackLayout,那么使用 BindableLayout 真的没有意义
  • 那么如何让 Stacklayout 显示在视图上呢?
  • page.Content = Items;
  • 可以吗?

标签: c# xaml xamarin xamarin.forms


【解决方案1】:

您只需将您动态创建的 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 }
    }
};
}

【讨论】:

    猜你喜欢
    • 2020-01-29
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    相关资源
    最近更新 更多