简体   繁体   中英

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

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

        <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.

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

Any alternatives that could work?

You should ItemsControl with ItemsSource bound to your source list. In ItemsControl.ItemsPanel you can set which panel you want to use for items. In your case you should use StackPanel with Orientation=Vertical as ItemsPanel . See first sample here . But vertical StackPanel is already default ItemsPanel so you can omit it.

Inner StackPanel should be specified as ItemTemplate in your ItemsControl .

Your XAML should look like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM