Created
November 19, 2021 00:52
-
-
Save deerchao/2dca42c998279968ffc79b06c78921fd to your computer and use it in GitHub Desktop.
WinForms StackPanel (Top to Bottom only)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class StackPanel : Panel | |
{ | |
private LayoutEngine _engine; | |
public StackPanel() | |
{ | |
HorizontalScroll.Maximum = 0; | |
AutoScroll = false; | |
VerticalScroll.Visible = false; | |
AutoScroll = true; | |
} | |
public override LayoutEngine LayoutEngine => _engine ??= new StackLayout(); | |
class StackLayout : LayoutEngine | |
{ | |
public override bool Layout(object container, LayoutEventArgs layoutEventArgs) | |
{ | |
if (container is not Control parent) | |
return false; | |
var bounds = parent.ClientRectangle; | |
bounds.Offset(parent.Padding.Left, parent.Padding.Top); | |
bounds.Inflate(-parent.Padding.Left - parent.Padding.Right, -parent.Padding.Top - parent.Padding.Bottom); | |
var startPoint = bounds.Location; | |
foreach (var c in parent.Controls.Cast<Control>().Reverse()) | |
{ | |
if (!c.Visible) | |
continue; | |
startPoint.Offset(c.Margin.Left, c.Margin.Top); | |
c.Location = startPoint; | |
if (c.AutoSize) | |
{ | |
c.Size = c.GetPreferredSize(bounds.Size); | |
} | |
else | |
{ | |
c.Width = bounds.Width - c.Margin.Left - c.Margin.Right; | |
} | |
startPoint.X = bounds.X; | |
startPoint.Y += c.Height + c.Margin.Bottom; | |
} | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment