自带的Label无法更改边框线的颜色以及边框大小,我们可以利用Paint事件自定义一个可以改变边框的label,代码如下:
public partial class CustomLabel : Label
{
public CustomLabel()
{
InitializeComponent();
this.SetStyle(ControlStyles.UserPaint, true);
}
private Color _borderColor = Color.Black;
private float _borderWidth = 0.5f;
/// <summary>
/// 边框颜色
/// </summary>
public Color BorderColor
{
get { return _borderColor; }
set { _borderColor = value; Invalidate(); }
}
/// <summary>
/// 边框宽度
/// </summary>
public float BorderWidth
{
get { return _borderWidth; }
set { _borderWidth = value; Invalidate(); }
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Pen pen = new Pen(_borderColor, _borderWidth))
{
e.Graphics.DrawRectangle(pen, 0, 0, this.Width - 1, this.Height - 1);
}
}
}
效果: