SingerOfTheFall
SingerOfTheFall

Reputation: 29986

How to properly position elements in a stack panel?

Let's say, I have a class that looks like this:

public class Item
{
    public string Name { get; set; }
    public List<Item> SubItems { get; set; }
}

I want to display a list of such items in such a way that top-level items are arranged horizontally, and their sub-elements are arranged vertically below them:

Item1      Item2        Item3      Item4
           SubItem2.1
           SubItem2.2

I'm trying to achieve that using a ListView, and my XAML looks like this:

<ListView x:Name="ItemsList">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical" VerticalAlignment="Top">
                <TextBlock Text="{Binding Name}" Background="#FF8686FF" Width="25" Height="25"/>
                <ListView ItemsSource="{Binding SubItems}" BorderBrush="{x:Null}">
                    <ListView.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}"/>
                        </DataTemplate>
                    </ListView.ItemTemplate>
                </ListView>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

However, my list doesn't look exactly the way I want:

enter image description here

As you can see, the items are vertically aligned to the center of their enclosing stack panels (which, in turn, occupy all available space). How do I properly align elements to the top? Or maybe there is a better way to achieve what I want with different containers?

Upvotes: 1

Views: 474

Answers (1)

Sinatr
Sinatr

Reputation: 22008

You have to set container style:

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="VerticalContentAlignment" Value="Top" />
    </Style>
</ListView.ItemContainerStyle>

Upvotes: 2

Related Questions