如何在 Carousel View 中向 DataTemplate 添加与列表元素数量一样多的标签?

How can I add as many labels as number of the list elements to DataTemplete in CarouselView?

我正在使用 Xamarin Forms 开发应用 PCL。

我想为每个项目创建一个带有不同数量按钮的轮播视图。

这是我的代码。

public class Main {
    ObservableCollection<Data> Datas = new ObservableCollection<Data>();
    /* add some data */
    CarouselView carouselView = new CarouselView();
    carouselView.SetBinding(ItemsView.ItemsSourceProperty, "Datas");
    carouselView.ItemTemplate = new DataTemplate(() =>{
        var layout = new StackLayout();
        Label titleLabel = new Label();
        titleLabel.SetBinding(Label.TextProperty, "Title");
        layout.Children.Add(titleLabel);
         
         //I want to do like this
         /*
         foreach(var body in Bodys) {
            var btn = new Button {
                Text = body
            };
            layout.Children.Add(btn);
        }
         */
        return layout;
    });

}

public class Data {
    public string Title { get; set; }
    public List<string> Bodys { get; set; } 
}

你有什么想法吗?

谢谢。

在您的情况下,您可以使用 Bindable Layouts

<CarouselView ItemsSource="{Binding Datas}">
        <CarouselView.ItemTemplate>
            <DataTemplate>
                <StackLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">

                    <Label Text="{Binding Title}"  />

                    <StackLayout BindableLayout.ItemsSource="{Binding Bodys}"  Orientation="Horizontal">
                        <BindableLayout.ItemTemplate>
                            <DataTemplate>
                                <StackLayout Margin="10" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
                                    <Button Text="{Binding .}"  />
                                </StackLayout>
                            </DataTemplate>
                        </BindableLayout.ItemTemplate>
                    </StackLayout>

                </StackLayout>
            </DataTemplate>
        </CarouselView.ItemTemplate>
    </CarouselView>

并且在您的 ViewModel 中

public ObservableCollection<Data> Datas {get; set;}