[英]How to remove padding in Label control?
How can totally remove padding in Label control?如何完全删除标签控件中的填充?
I tried to set Margin and Padding properties to zero, but still I have few pixels of margin inside Label.我试图将 Margin 和 Padding 属性设置为零,但标签内的边距像素仍然很少。
I want zero or very small (less than half of "space" character width) left and right padding in Windows Forms.我希望 Windows 窗体中的左右填充为零或非常小(小于“空格”字符宽度的一半)。
I need this for label placed very close to other, but when I place labels very close - background of label placed on top covers other label text.对于与其他标签非常接近的标签,我需要使用它,但是当我将标签非常接近时 - 放置在顶部的标签背景会覆盖其他标签文本。 I use right align on one label, left on other label and it looks like this:我在一个标签上使用右对齐,在另一个标签上使用左对齐,它看起来像这样:
I have this problem regardless of AutoSize property.无论 AutoSize 属性如何,我都有这个问题。 There is always too much padding on right side of control.控件右侧总是有太多填充。
In WPF it works as I want, but I have to use Windows Forms.在 WPF 中,它可以按我的意愿工作,但我必须使用 Windows 窗体。
I can't use TextBox control (where it works as I want), because it does not support transparent background.我不能使用 TextBox 控件(它可以随心所欲地工作),因为它不支持透明背景。
You can totally remove padding if you draw the text yourself. 如果您自己绘制文本,则可以完全删除填充。 Here is a simple custom label control (RightAlignment property changes text alignment) 这是一个简单的自定义标签控件(RightAlignment属性更改文本对齐)
public partial class NoPaddingLabel : Label
{
private TextFormatFlags flags = TextFormatFlags.SingleLine | TextFormatFlags.VerticalCenter | TextFormatFlags.Left | TextFormatFlags.NoPadding;
public bool RightAlignment
{
get
{
return (flags & TextFormatFlags.Right) == TextFormatFlags.Right;
}
set
{
if (value)
{
flags = flags |= TextFormatFlags.Right;
}
else
{
flags = flags &= ~TextFormatFlags.Right;
}
Invalidate();
}
}
public NoPaddingLabel()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
TextRenderer.DrawText(e.Graphics, this.Text, this.Font, ClientRectangle, this.ForeColor, Color.Transparent, flags);
}
}
尝试将UseCompatibleTextRendering属性设置为true 。
I used a Canvas layout to solve this:我使用 Canvas 布局来解决这个问题:
<Canvas>
<Label Canvas.Left="35" Canvas.Top="0" Content="Latitude:" HorizontalAlignment="Right" Foreground="red"/>
<Label Canvas.Left="90" Canvas.Top="0" Content="nn.nnnnnn" Foreground="red" />
<Label Canvas.Left="25" Canvas.Top="12" Content="Longitude:" HorizontalAlignment="Right" Foreground="red"/>
<Label Canvas.Left="90" Canvas.Top="12" Content="nn.nnnnnn" Foreground="red" />
<Label Canvas.Left="40" Canvas.Top="26" Content="Date" HorizontalAlignment="Center" Foreground="Blue"/>
<Label Canvas.Left="100" Canvas.Top="26" Content="Time" HorizontalAlignment="Center" Foreground="Blue"/>
</Canvas>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.