Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the margins around text in a WPF label?

I am trying to make a little virtual keyboard out of labels. The following is my keyboard in XAML (but with more than just 3 keys):

<StackPanel Orientation="Vertical">
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <Border BorderThickness="1" BorderBrush="DarkGray">
            <Label Content="A" FontSize="12" MouseDown="KeyButton_Click" />
        </Border>
        <Border BorderThickness="1" BorderBrush="DarkGray">
            <Label Content="B" FontSize="12" MouseDown="KeyButton_Click" />
        </Border>
    </StackPanel>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <Border BorderThickness="1" BorderBrush="DarkGray">
            <Label Content="C" FontSize="12" MouseDown="KeyButton_Click" />
        </Border>
    </StackPanel>
</StackPanel>

The problem with this is that there is too much space surrounding the text in the labels, causing the keyboard to be much bigger than it needs to be. If I manually set the height and width of the labels, that will (1) not account for differences in fonts and (2) will cut of part of the letter rather than the top and left margins. Is there any other way to shrink these margins to be just about the same size as the text itself?

like image 583
Matt Avatar asked Jul 16 '12 09:07

Matt


People also ask

How do I set margins in WPF?

The Margin property of UIElement, which is parent class of all WPF controls is used to set the margin of a control. Margin property takes four numbers - Left, Top, Right and Bottom, that is margin to the left top and right bottom.

What is margin in WPF?

wpf. The margin property in WPF allows you set spacing between elements in a window. You can assign the margins for the Top, Right, Bottom and Left. Every control that derives from FrameworkElement has this property.

What is padding in WPF?

Padding represents the distance between the side of the control (which can be the margin) and its content. The content depends on the type of the control. Margin is outside the UI element, while Padding is inside it. Next Recommended Reading WPF: Textblock Vs Label.

How do I center text in a label in WPF?

If you want to center each line, use a TextBlock instead, and set TextAlignment="Center" .


1 Answers

Set padding to 0.

I had the same problem. Upon examining the properties of a label in the properties window, I discovered the default padding of a label is 5. Setting it to 0 did the trick.

like image 72
Shaggydog Avatar answered Oct 01 '22 23:10

Shaggydog