代码之家  ›  专栏  ›  技术社区  ›  jyoung

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

  •  0
  • jyoung  · 技术社区  · 17 年前

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

    我已经没有办法把垂直线放在哪里了。

    <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; }
        }
    }
    
    1 回复  |  直到 15 年前
        1
  •  2
  •   rmoore    17 年前

    您需要在列表框中设置VerticalContentAlignment,设置之后,您在列表框中的所有其他对齐也可以删除。

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

    列表框上VerticalContentLightment的默认值是“Center”,因此即使您在其他地方设置了VerticalAlignment,它也只是与列表框项的顶部对齐,这些项仍然居中,而不是拉伸或放置在顶部。如果将VerticalContentAlignment设置为Stretch,那么您将看到另一个VerticalAlignment=“top”声明起作用。