本文共 2255 字,大约阅读时间需要 7 分钟。
布局器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常规自动填充工具箱:设为True2添加自定义Panel或Control的类 3生成解决方案F74重新打开Form1.cs,在工具箱界面可以看到自己的控件
FlowLayoutPanel,流式布局
子控件依次排列,一行排满之后换行继续排1布局的嵌套
Panel本身也是控件,也有Anchor/Dock属性2属性的设置
试着设一下Padding等属性3控件的选择
右键,选择控件或该控件所在的面板TableLayoutPanel,表格布局
以表格的形式进行布局演示:使用TableLayoutPanel来布局界面
1 添加TableLayoutPanel,停靠在上方2 添加Button , TextBox到表格,设置列的宽度3 设置TextBox的Dock,填满单元格4 添加PictureBox,停靠在中央
表格中的控件也可以设置Dock属性
如何利用Dock属性,其规则是由布局器决定的比如,默认的Dock停靠布局并不好用
演示对比: 第一种情况:先Left后 Fill 第二种情况:先Fill后Left 最终的布局效果依赖于控件添加的顺序,非常不方便1 添加Mj.Winform.DockLayout.cs到项目2 重新生成项目3 在工具箱里找到MjDockLayout,添加到布局4 在面板中添加子控件,设置Dock5 设置MjDockLayout.DockFlags属性
转载地址:http://vzdtz.baihongyu.com/