布 局 器 布局器 布局器
1.布局器
布局器LayoutEngine:负责子控件的布局
默认地,一个Form或Panel 都自带了一个布局器
在窗口改变大小时,由窗口的布局器来负责调整布局
SimpleLayoutPanel :自定义一个Panel,并自己实现一个LayoutEngine
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Forms.Layout;
namespace FormApp0601
{
// 自定义面板
class SimpleLayoutPanel : Panel
{
// 布局器
private LayoutEngine layoutEngine = new SimpleLayoutEngine();
public override LayoutEngine LayoutEngine
{
get
{
return layoutEngine;
}
}
}
// 自定义布局器
class SimpleLayoutEngine : LayoutEngine
{
public override bool Layout(
object container,
LayoutEventArgs layoutEventArgs)
{
// 容器
SimpleLayoutPanel parent = (SimpleLayoutPanel)container;
int w = parent.Width;
int h = parent.Height;
// 去除Padding
int x = parent.Padding.Left;
int y = parent.Padding.Top;
w -= (parent.Padding.Left + parent.Padding.Right);
h -= (parent.Padding.Top + parent.Padding.Bottom);
int gap = 2;
foreach (Control c in parent.Controls)
{
c.Location = new Point(x, y);
c.Size = new Size(w, c.PreferredSize.Height);
y += c.Size.Height;
y += gap;
}
return false;
}
}
}
自定义布局器的使用步骤:
1工具I选项,Windows窗体设计器I常规
自动填充工具箱:设为True
2添加自定义Panel或Control的类
3生成解决方案F7
4重新打开Form1.cs,在工具箱界面可以看到自己的控件
2.FlowLayoutPanel
FlowLayoutPanel,流式布局
子控件依次排列,一行排满之后换行继续排
1布局的嵌套
Panel本身也是控件,也有Anchor/Dock属性
2属性的设置
试着设一下Padding等属性
3控件的选择
右键,选择控件或该控件所在的面板
3.TableLayoutPanel
TableLayoutPanel,表格布局
以表格的形式进行布局
演示:使用TableLayoutPanel来布局界面
1 添加TableLayoutPanel,停靠在上方
2 添加Button , TextBox到表格,设置列的宽度
3 设置TextBox的Dock,填满单元格
4 添加PictureBox,停靠在中央
表格中的控件也可以设置Dock属性
如何利用Dock属性,其规则是由布局器决定的
4.MjDockLayout
比如,默认的Dock停靠布局并不好用
演示对比:
第一种情况:先Left后 Fill
第二种情况:先Fill后Left
最终的布局效果依赖于控件添加的顺序,非常不方便
1 添加Mj.Winform.DockLayout.cs到项目
2 重新生成项目
3 在工具箱里找到MjDockLayout,添加到布局
4 在面板中添加子控件,设置Dock
5 设置MjDockLayout.DockFlags属性