wpf 如何使用可变数量的 StackPanel 的 StackPanel 创建 DataTemplate

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13195494/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 06:02:56  来源:igfitidea点击:

How to create a DataTemplate with a StackPanel of a variable number of StackPanels

c#wpfdatatemplatestackpanel

提问by adi burus

I am trying to create a DataTamplate which should contain a StackPanel with a certain number of StackPanels.

我正在尝试创建一个 DataTamplate,它应该包含一个具有一定数量 StackPanel 的 StackPanel。

        <DataTemplate x:Key="DataTemplate">
        <StackPanel Orientation="Vertical">
            <StackPanel Orientation="Horizontal">
                <Rectangle Fill="Aqua" Margin="2" Height="100" Width="50"  VerticalAlignment="Top" HorizontalAlignment="Left"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>

The code snippet above is just for a better understanding of my desired result, as the elements in the imbricated StackPanel will be binded.

上面的代码片段只是为了更好地理解我想要的结果,因为叠片 StackPanel 中的元素将被绑定。

This generates the following error message: VisualTree of ItemsPanelTemplate must be a single element.

这会生成以下错误消息: ItemsPanelTemplate 的 VisualTree 必须是单个元素。

Any alternatives that could work?

任何可行的替代方案?

回答by Snowbear

You should ItemsControlwith ItemsSourcebound to your source list. In ItemsControl.ItemsPanelyou can set which panel you want to use for items. In your case you should use StackPanelwith Orientation=Verticalas ItemsPanel. See first sample here. But vertical StackPanelis already default ItemsPanelso you can omit it.

你应该ItemsControlItemsSource绑定到你的源列表。在ItemsControl.ItemsPanel你可以设置你要使用的物品,其面板。在您的情况下,您应该使用StackPanelwith Orientation=Verticalas ItemsPanel。请参阅此处的第一个示例。但是垂直StackPanel已经是默认的,ItemsPanel所以你可以省略它。

Inner StackPanelshould be specified as ItemTemplatein your ItemsControl.

InnerStackPanel应该ItemTemplate在您的ItemsControl.

Your XAML should look like this:

您的 XAML 应如下所示:

<ItemsControl ItemsSource="...">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <!-- properties of your object should go here -->
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>