[英]Aligning TextBlock Vertically Inside StackPanel
In my WPF application I have a DataGrid
with multiple DataGridTemplateColumns
. 在我的WPF应用程序我有一个DataGrid
有多个DataGridTemplateColumns
。 One of the columns looks like this: 列之一如下所示:
<DataGridTemplateColumn Header="Column" Width="*">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<ListBox ItemsSource="{Binding SomeSource}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Margin="5"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Green" HorizontalAlignment="Center" VerticalAlignment="Center" CornerRadius="6" BorderThickness="2">
<StackPanel Background="Green" Width="200" Height="150">
<TextBlock Text="{Binding Title}" HorizontalAlignment="Center" FontSize="17" FontWeight="Bold" />
</StackPanel>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
This produces the following output: 这将产生以下输出:
As you can see the TextBlock
which displays the Title
is not vertically centered inside the green StackPanel
. 如您所见,显示Title
的TextBlock
不在绿色StackPanel
垂直居中。 How can I do that? 我怎样才能做到这一点?
StackPanel
doesn't have a concept of its height, so you can't vertically-align its children. StackPanel
没有高度的概念,因此您无法垂直对齐其子级。 You'll have to do something a bit differently. 您必须做一些不同的事情。
For example, move the fixed 150-height and background from the StackPanel to its parent border -- that way, you can vertically-align the StackPanel within the Border: 例如,将固定的150高度和背景从StackPanel移至其父边框-这样,您可以在Border内垂直对齐StackPanel:
<Border Background="Green" Height="150" BorderBrush="Green" HorizontalAlignment="Center" VerticalAlignment="Center" CornerRadius="6" BorderThickness="2">
<StackPanel Width="200" VerticalAlignment="Center">
<TextBlock Text="{Binding}" HorizontalAlignment="Center" FontSize="17" FontWeight="Bold" />
</StackPanel>
</Border>
(It's not really clear why you're using that inner StackPanel since it only has one child, but I've assumed you're going to add something else to it.) (目前尚不清楚您为什么要使用该内部StackPanel,因为它只有一个孩子,但是我假设您要为其添加其他内容。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.