- 背景:在窗体开发中使控件的位置不随窗体的大小改变而变化的问题?这是一个同事在开发时遇到的问题,在思考试错之后,写出如下代码。
- 声明成员:
Point m_InitLocation;
Size m_InitFormSize;
double scale = ;
Size m_CurrentFormSize;
Point m_CurrentTBLocation;
- 主要代码:
private void XtraForm1_SizeChanged(object sender, EventArgs e)
{
m_CurrentFormSize = this.Size; scale = (double)((double)m_CurrentFormSize.Height / (double)m_InitFormSize.Height);
m_CurrentTBLocation.Y = (int)(m_InitLocation.Y * scale); scale = (double)((double)m_CurrentFormSize.Width / (double)m_InitFormSize.Width);
m_CurrentTBLocation.X = (int)(m_InitLocation.X * scale); textEdit1.Location = m_CurrentTBLocation; }
这样textEdit1控件就不会随窗体大小的变化而改变位置。
- 使用扩张方法:
public static class textExtension
{
public static Point NewSize(this DevExpress.XtraEditors.TextEdit textedit, Size oldSize, Size newSize, Point oldtextPoint)
{
double scale = ;
Point location = new Point();
scale = (double)((double)newSize.Height / (double)oldSize.Height);
location.Y = (int)(oldtextPoint.Y * scale); scale = (double)((double)newSize.Width / (double)oldSize.Width);
location.X = (int)(oldtextPoint.X * scale); return location; }
}
此时XtraForm1_SizeChanged函数中只需加入一行代码即可:
this.textEdit1.Location = textEdit1.NewSize(m_InitFormSize, this.Size, m_InitLocation);
- 总结:使用扩张方法,在控件多的时候非常方便,没加入一个控件XtraForm1_SizeChanged函数中就只用加入一行代码。清晰简洁易于修改扩张。