简体   繁体   中英

Aligning TextBlock Vertically Inside StackPanel

In my WPF application I have a DataGrid with multiple 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 . How can I do that?

StackPanel doesn't have a concept of its height, so you can't vertically-align its children. 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:

<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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM