我正在使用一个分组框,其中有几个控件。
我的要求是将组框标题设置为组框的中间而不是左侧。
如何?
答案 0 :(得分:3)
不幸的是,您可以使用RightToLeft属性在右侧设置标题,但没有属性可以将其设置在中间。
您可以做的是在GroupBox中设置一个空文本,使用标题创建一个Label,并将该标签放在GroupBox上方(使用相同的父级)。
您可以通过调用以下过程在表单初始化中动态执行此操作:
private void CenterGroupBoxTitle(GroupBox groupbox)
{
Label label = new Label() ;
label.Text = groupbox.Text ;
groupbox.Text = "" ;
label.Left = groupbox.Left+(groupbox.Width-label.Width)/2 ;
label.Top = groupbox.Top + 2 ; // 2 is an example : adjust the constant
label.Parent = groupbox.Parent ;
label.BringToFront() ;
}
答案 1 :(得分:3)
您可以像这样扩展群组类。
row[1]
将上述类添加到您的项目中并使用“CustomGrpBox”而不是“GroupBox”,它将在您的工具箱中构建后创建。
你可以随时设置文字。
public class CustomGrpBox : GroupBox
{
private string _Text = "";
public CustomGrpBox()
{
//set the base text to empty
//base class will draw empty string
//in such way we see only text what we draw
base.Text = "";
}
//create a new property a
[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));
}
}
它将在设计时间视觉工作室中看起来像这样
答案 2 :(得分:1)
尝试使用public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
SplashFragment splashFragment = new SplashFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container,splashFragment).commit();
}
public void onLoad(){
MainFragment mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container,mainFragment).commit();
}
}
作为容器创建自定义控件并在其周围绘制边框,然后您就可以完全控制标题的对齐方式。
如果您想要一种简单的方法,可以将组框的标题保留为空文本,然后将Panel
放在组框的中心位置。您也可以将其定义为用户控件,这样您就不需要重复这样做了。
答案 3 :(得分:0)
不是一个雄辩的解决方案,但是如果你有一个简单的GroupBox,那就是(相同的大小,你可以填充开头,结尾有空格。
示例:GroupBox.Text = " This is the groupbox text ";
空间的填充量取决于盒子的长度。 当然,你会丢失一些GroupBox的起点和终点,如果这很重要,那么答案3似乎是一个很好的解决方案。