日期:2014-05-18  浏览次数:21169 次

GroupBox的标题居中或居右
如题,怎样做到?

------解决方案--------------------
加一个自定义GroupBox控件,加TextAlignment属性,重写OnPainting方法,新建Text属性
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace TestTemplate
{
public partial class grp : GroupBox
{
public grp()
{
InitializeComponent();
base.Text = "";
}
private string text;
public new string Text
{
get
{
return this.text;
}
set
{
base.Text = "";
this.text = value;
}
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
StringFormat s = new StringFormat();
s.LineAlignment = StringAlignment.Near;
s.Alignment = this.textAlignment;
e.Graphics.DrawString(this.text, this.Font, Brushes.Black, new RectangleF(0, 0, this.Width, this.Height), s);
}
private StringAlignment textAlignment = StringAlignment.Center;

public StringAlignment TextAlignment
{
get { return textAlignment; }
set { textAlignment = value; }
}

}
}

------解决方案--------------------
可以这样去处理:
在onpaint 事件里:
base.OnPaint(e);
StringFormat s = new StringFormat();
s.LineAlignment = StringAlignment.Near;
s.Alignment = this.textAlignment;
//新增如下代码段--------------------
SizeF textarea= e.Graphics.MeasureString(this.Text, this.Font);
Brush a = new SolidBrush(this.BackColor);
e.Graphics.FillRectangle(a, new RectangleF(5, 0, (this.Width - 10) * 1.0f, textarea.Height));
//--------------------------------
e.Graphics.DrawString(this.Text, this.Font, Brushes.Black, new RectangleF(0, 0, this.Width, this.Height), s);