tags:

views:

65

answers:

1

In a horizontal listbox how do I align items to the top?

I have ran out of ideas of where to stick a VerticalAlignment="Top".

<Window.Resources>
    <DataTemplate DataType="{x:Type l:MyType}">
        <Grid VerticalAlignment="Top">
            <TextBlock VerticalAlignment="Top" Text="{Binding MyValue}" Background="Yellow"/>
        </Grid>
    </DataTemplate>    
</Window.Resources>   

<Grid>
    <ListBox Name="listBox" ItemsSource="{Binding}"  VerticalAlignment="Top" >

        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal" VerticalAlignment="Top"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>

        <ListBox.ItemTemplate>
            <DataTemplate>
                <ListBoxItem Content="{Binding}" VerticalAlignment="Top" VerticalContentAlignment="Top"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

using System.Windows;

namespace WpfApplication5 {
    public partial class Window1 :Window {
        public Window1() {
            InitializeComponent();
            this.listBox.ItemsSource = new MyType[] {
                new MyType{ MyValue = "Tall\nItem" },
                new MyType{ MyValue = "I want this aligned to the top" } };
        }
    }

    public class MyType {
        public string MyValue { get; set; }
    }
}
A: 

You need to set the VerticalContentAlignment on the list box, all the other alignments you have in there can be removed as well once that is set.

....
<ListBox Name="listBox" ItemsSource="{Binding}"  VerticalContentAlignment="Top" >
....

The default for the VerticalContentAlightment on your ListBox is 'Center', so even though you were setting the VerticalAlignment elsewhere it was just aligning to the top of the ListBoxItems, which were still centered instead of streched or placed at the top. If you set the VerticalContentAlignment to Stretch then you'd see the other VerticalAlignment="Top" declarations work.

rmoore
Arrrrrg, so simple.Thanks.
jyoung