2009-06-24 35 views
0

在水平列表框中,如何将项目对齐到顶部?在水平列表框中,如何将项目对齐到顶部?

我已经跑出想要粘贴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; } 
    } 
} 

回答

2

您需要设置VerticalContentAlignment列表框,你有其他的路线在那里可以和一旦被设置删除。

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

你的列表框的VerticalContentAlightment默认为“中心”,所以即使你在其他地方设置VerticalAlignment这只是对准了ListBoxItems的顶部,仍然集中,而不是streched或放置在顶端。如果你将VerticalContentAlignment设置为Stretch,那么你会看到另一个VerticalAlignment =“Top”声明工作。

+0

Arrrrrg,这么简单。 谢谢。 – jyoung 2009-06-24 21:50:03

相关问题