如何在堆栈面板中正确定位元素?
How to properly position elements in a stack panel?
比方说,我有一个 class 看起来像这样:
public class Item
{
public string Name { get; set; }
public List<Item> SubItems { get; set; }
}
我想以这样的方式显示此类项目的列表,即顶级项目水平排列,其子元素垂直排列在其下方:
Item1 Item2 Item3 Item4
SubItem2.1
SubItem2.2
我正在尝试使用 ListView
来实现这一点,我的 XAML 看起来像这样:
<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>
但是,我的列表看起来并不完全符合我的要求:
如您所见,项目垂直对齐到其封闭堆栈面板的中心(依次占据所有可用 space)。如何正确地将元素对齐到顶部?或者也许有更好的方法来实现我想要的不同容器?
您必须设置容器样式:
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="VerticalContentAlignment" Value="Top" />
</Style>
</ListView.ItemContainerStyle>
比方说,我有一个 class 看起来像这样:
public class Item
{
public string Name { get; set; }
public List<Item> SubItems { get; set; }
}
我想以这样的方式显示此类项目的列表,即顶级项目水平排列,其子元素垂直排列在其下方:
Item1 Item2 Item3 Item4
SubItem2.1
SubItem2.2
我正在尝试使用 ListView
来实现这一点,我的 XAML 看起来像这样:
<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>
但是,我的列表看起来并不完全符合我的要求:
如您所见,项目垂直对齐到其封闭堆栈面板的中心(依次占据所有可用 space)。如何正确地将元素对齐到顶部?或者也许有更好的方法来实现我想要的不同容器?
您必须设置容器样式:
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="VerticalContentAlignment" Value="Top" />
</Style>
</ListView.ItemContainerStyle>