Search code examples
c#wpfxamlalignmentblock

Textblock's content is not centered


View of the buttons

Hi sof, recently i made a resource dictionary. I streched my button to the grid's height and at the resource dictionary in the textblock of button's content presenter section, i changed the horizontal and vertical content alignment to center like below;

<Style x:Key="RButtonStyle" TargetType="Button">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <TextBlock x:Name="b" 
                      HorizontalAlignment="Center" 
                      VerticalAlignment="Center">
                   <ContentPresenter 
                      HorizontalAlignment="Center" 
                      VerticalAlignment="Center" />
              ...

and yes, it worked. But not perfectly. See the link above and have a look to what i'm saying. Where can i get some detailed info about it, or can you help me about this?

I did not changed anything on textblock's content section except for this. If you want the full code of my resource dictionary i may post it for you.


Solution

  • So since you're using TextBlock directly, you need just set the TextAlignment property to "Center" to get your centered text as HorizontalContentAlignment property is not present in TextBlock.

    So;

    <TextBlock x:Name="b" 
               HorizontalAlignment="Center" 
               VerticalAlignment="Center"
               TextAlignment="Center"/>
    

    However, unless I'm mistaken, you need a parent panel for your control template as it should error currently if Content of Button is filled since there's more than one child in the object tree. So you'll also want to add something to house the children like a simple Grid or StackPanel etc.

    Like;

    <ControlTemplate TargetType="Button">
       <Grid>
          <TextBlock x:Name="b" 
                     HorizontalAlignment="Center" 
                     VerticalAlignment="Center"
                     TextAlignment="Center"/>
          <ContentPresenter 
                     HorizontalAlignment="Center" 
                     VerticalAlignment="Center"/>
       </Grid>
    </ControlTemplate>
    

    If you wanted to use the HorizontalContentAlignment property of Button you need to include it in your template somewhere.

    Like for example;

    <TextBlock x:Name="b" 
               HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" 
               VerticalAlignment="Center"/>
    

    Hope this helps, cheers!