文章开始之前,先看下图,红圈的GroupBox文字是如何居中的呢?
我们都知道,自带的Winform中的GroupBox组件的标题,是不具备居中功能的。要实现这个功能,只能自己复写BroupBox控件。
下面直接贴出代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace RevitDevelopment.CustomControls
{
///
/// 框
///
/// marc
public class Frame : GroupBox
{
private string _text = "";
///
/// 构造函数
///
public Frame()
{
base.Text = "";
}
[Browsable(true)]
[Category("Appearance")]
[DefaultValue("GroupBoxText")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public new string Text
{
get
{
return _text;
}
set
{
_text = value;
this.Invalidate();
}
}
///
/// 重绘
///
///
protected override void OnPaint(PaintEventArgs e)
{
//first let the base class to draw the control
base.OnPaint(e);
//create a brush with fore color
SolidBrush colorBrush = new SolidBrush(this.ForeColor);
//create a brush with back color
var backColor = new SolidBrush(this.BackColor);
//measure the text size
var size = TextRenderer.MeasureText(this.Text, this.Font);
// evaluate the postiong of text from left;
int left = (this.Width - size.Width) / 2;
//draw a fill rectangle in order to remove the border
e.Graphics.FillRectangle(backColor, new Rectangle(left, 0, size.Width, size.Height));
//draw the text Now
e.Graphics.DrawString(this.Text, this.Font, colorBrush, new PointF(left, 0));
}
}
}
编写上面的自定义控件,自己保存起来。然后编译后,在“工具箱”中就可以找到这个控件了:
直接将这个控件拖入自己需要的地方,然后设置以下属性即可:
最后效果就出来了:
祝您用餐愉快。