Text content in a WPF button not being centred vertically

前端 未结 2 1176
日久生厌
日久生厌 2021-02-12 13:38

Is there a reason why the text content of a WPF button is appearing with unwanted space above the text?

I have a button in a StackPanel. This button is a simple close b

相关标签:
2条回答
  • 2021-02-12 14:08

    A simple way to accomplish this with a lower case "x" is to use a TextBlock as content and play with its upper margin:

    <Button Command="{Binding myCommand}">
        <TextBlock Text="x" Margin="0,-3,0,0"/>
    </Button>
    
    0 讨论(0)
  • 2021-02-12 14:10

    My guess is that you see this problem because there's a conflict between the height you gave it and the space it actually needs to render itself properly.

    Things you can do to solve this:

    • Play with the Padding property of the button. This controls the space between the text and the button borders.
    • Reduce the font size.
    • Don't put an explicit height on the button, or at least give it a height large enough to accommodate for the font size and padding you want.

    Also, as mentioned by Heinzi in the comments you should of course use an uppercase X.

    By the way, here's a trick you can use if you want to make the button be a proper square while making sure the button gets the size it needs.

    <Button Padding="0" 
        Width="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=ActualHeight}" 
        HorizontalContentAlignment="Center" VerticalContentAlignment="Center"
        FontSize="12" Content="X" />
    

    This effectively lets the button decide what height it needs and then you set the Width to that calculated value.

    0 讨论(0)
提交回复
热议问题