110,580
社区成员
发帖
与我相关
我的任务
分享
public class BorderedTableLayoutPanel : TableLayoutPanel
{
Pen borderPen;
public Pen BorderPen { get { return this.borderPen; } set { this.borderPen = value; } }
protected override void OnCreateControl()
{
base.OnCreateControl();
this.CellBorderStyle = TableLayoutPanelCellBorderStyle.None;
this.borderPen = this.borderPen == null ? Pens.DarkGray : this.borderPen;
this.ControlAdded += delegate { this.cellBorders = null; };
this.ControlRemoved += delegate { this.cellBorders = null; };
}
protected override void OnCellPaint(TableLayoutCellPaintEventArgs e)
{
base.OnCellPaint(e);
Pen pen = this.BorderPen;
Borders borders = this[e.Row, e.Column];
Point topleft = new Point(e.CellBounds.Left, e.CellBounds.Top);
Point topright = new Point(e.CellBounds.Right - 1, e.CellBounds.Top);
Point bottomleft = new Point(e.CellBounds.Left, e.CellBounds.Bottom - 1);
Point bottomright = new Point(e.CellBounds.Right - 1, e.CellBounds.Bottom - 1);
if ((borders & Borders.Left) == Borders.Left) e.Graphics.DrawLine(pen, topleft, bottomleft);
if ((borders & Borders.Right) == Borders.Right) e.Graphics.DrawLine(pen, topright, bottomright);
if ((borders & Borders.Top) == Borders.Top) e.Graphics.DrawLine(pen, topleft, topright);
if ((borders & Borders.Bottom) == Borders.Bottom) e.Graphics.DrawLine(pen, bottomleft, bottomright);
}
[Flags]
enum Borders
{
None = 0, Left = 1, Right = 2, Top = 4, Bottom = 8,
}
Borders[,] cellBorders;
Borders this[int row, int col]
{
get
{
if (this.cellBorders == null)
{
PrepareCellBorders();
}
if (row < this.cellBorders.GetLength(0) && col < this.cellBorders.GetLength(1))
{
return this.cellBorders[row, col];
}
return Borders.None;
}
set
{
if (this.cellBorders == null)
{
PrepareCellBorders();
}
if (row < this.cellBorders.GetLength(0) && col < this.cellBorders.GetLength(1))
{
this.cellBorders[row, col] = value;
}
}
}
private void PrepareCellBorders()
{
this.cellBorders = new Borders[this.RowCount, this.ColumnCount];
for (int y = 0; y < cellBorders.GetLength(0); y++)
{
for (int x = 0; x < cellBorders.GetLength(1); x++)
{
cellBorders[y, x] = Borders.Top | Borders.Left;
if (y == cellBorders.GetLength(0) - 1) cellBorders[y, x] |= Borders.Bottom;
if (x == cellBorders.GetLength(1) - 1) cellBorders[y, x] |= Borders.Right;
}
}
foreach (Control c in this.Controls)
{
int rowspan = this.GetRowSpan(c);
int colspan = this.GetColumnSpan(c);
TableLayoutPanelCellPosition pos = this.GetCellPosition(c);
for (int y = 0; y < rowspan; y++)
{
for (int x = 0; x < colspan; x++)
{
if (y > 0) this[pos.Row + y, pos.Column + x] &= ~Borders.Top;
if (x > 0) this[pos.Row + y, pos.Column + x] &= ~Borders.Left;
}
}
}
}
}