WPF: Textblock as item in ComboBox: how to center the text of Textblock vertically?

2.4k views Asked by At

I use WPF 4.5, Caliburn Micro 2, VS2013. I use TextBlock as item in ComboBox.

The height of ComboBox is 80.

The height of TextBlock is 50.

The font size of text inside the TextBlock is standard.

My following sample xaml code works but it shows the text not vertically centered in TextBlock. How to make the text vertically centered with/without changing the height of TextBlock to Auto? Thank you in advance.

<ComboBox Width="150"
          Height="80"
          VerticalContentAlignment="Center"
          ItemsSource="{Binding Path=Locations}"
          SelectedIndex="0"
          SelectedItem="{Binding Path=SelectedLocation,
                                 Mode=OneWayToSource}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Height="50"
                       HorizontalAlignment="Stretch"
                       VerticalAlignment="Center"
                       Background="Aquamarine"
                       Text="{Binding Path=Address}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And here is the screenshot:

enter image description here

2

There are 2 answers

0
Krishna On BEST ANSWER

A TextBlock should not have a height but its container should instead. If you want to set the background color for your TextBlock then wrap your TextBlock in a Border or a Grid and set the height on them instead.

Like

<Grid Height="50>
     <TextBlock VerticalAlignment="Center" Text....../>
</Grid>
1
Freddy On

Text-Align="center" or you could use a margin on each of the sides.