Panel
ThePanel class is the base class for all controls that can contain multiple children. It provides the foundation for layout containers like Grid, StackPanel, Canvas, and DockPanel.
Namespace
Inheritance
Properties
Gets the collection of child controls.This is a
Controls collection that supports adding, removing, and clearing children.Gets or sets the panel’s background brush.The background is rendered behind all children.
Gets whether the panel hosts items created by an ItemsPresenter.This is set internally when the panel is used as an ItemsPanel.
Methods
Renders the panel and its background.Parameters:
context(DrawingContext): The drawing context
Usage Examples
Basic Panel Usage
The base
Panel class doesn’t provide any layout logic - children overlap at position (0,0). Use derived classes like Grid or StackPanel for automatic layout.Custom Panel
Create a custom panel by deriving from Panel:Managing Children in Code
Setting Background
Built-in Panel Types
Avalonia provides several specialized panel types:Grid
Flexible grid layout with rows and columns
StackPanel
Stacks children horizontally or vertically
DockPanel
Docks children to edges (top, bottom, left, right)
Canvas
Absolute positioning with Left, Top, Right, Bottom
WrapPanel
Wraps children to next line when space runs out
UniformGrid
Evenly-sized cells in rows and columns
Creating Custom Panels
When creating custom panels, override these methods:MeasureOverride
Calculate desired size:ArrangeOverride
Position and size children:Best Practices
Choose the right panel for the job
Choose the right panel for the job
Each panel type has specific strengths:
- Grid: Complex layouts with aligned elements
- StackPanel: Simple lists or toolbars
- DockPanel: Application frames with sidebars/headers
- Canvas: Absolute positioning for diagrams/games
Measure children before using their DesiredSize
Measure children before using their DesiredSize
Always call
child.Measure() before accessing child.DesiredSize.Consider virtualization for large lists
Consider virtualization for large lists
For panels with many children, consider implementing virtualization to only create visible items.