In this article

Panels Overview

In this article

Panel elements are components that control the rendering of elements—their size and dimensions, their position, and the arrangement of their child content. The Windows Presentation Foundation (WPF) provides a number of predefined Panel elements as well as the ability to construct custom Panel elements.

The Panel Class

Panel is the base class for all elements that provide layout support in Windows Presentation Foundation (WPF). Derived Panel elements are used to position and arrange elements in Extensible Application Markup Language (XAML) and code.

The WPF includes a comprehensive suite of derived panel implementations that enable many complex layouts. These derived classes expose properties and methods that enable most standard user interface (UI) scenarios. Developers who are unable to find a child arrangement behavior that meets their needs can create new layouts by overriding the ArrangeOverride and MeasureOverride methods. For more information on custom layout behaviors, see Custom Panel Elements.

Panel exposes additional properties that are of critical importance in understanding and using layout. The Background property is used to fill the area between the boundaries of a derived panel element with a Brush. Children represents the child collection of elements that the Panel is comprised of. InternalChildren represents the content of the Children collection plus those members generated by data binding. Both consist of a UIElementCollection of child elements hosted within the parent Panel.

Panel also exposes a Panel.ZIndex attached property that can be used to achieve layered order in a derived Panel. Members of a panel's Children collection with a higher Panel.ZIndex value appear in front of those with a lower Panel.ZIndex value. This is particularly useful for panels such as Canvas and Grid which allow children to share the same coordinate space.

Panel also defines the OnRender method, which can be used to override the default presentation behavior of a Panel.

Attached Properties

Derived panel elements make extensive use of attached properties. An attached property is a specialized form of dependency property that does not have the conventional common language runtime (CLR) property "wrapper". Attached properties have a specialized syntax in Extensible Application Markup Language (XAML), which can be seen in several of the examples that follow.

One purpose of an attached property is to allow child elements to store unique values of a property that is actually defined by a parent element. An application of this functionality is having child elements inform the parent how they wish to be presented in the user interface (UI), which is extremely useful for application layout. For more information, see Attached Properties Overview.

WrapPanel positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box. Subsequent ordering happens sequentially from top to bottom or right to left, depending on the value of the Orientation property.

More detailed descriptions and usage examples of each of these elements can be found below.

Canvas

The Canvas element enables positioning of content according to absolute x- and y-coordinates. Elements can be drawn in a unique location; or, if elements occupy the same coordinates, the order in which they appear in markup determines the order in which the elements are drawn.

Canvas provides the most flexible layout support of any Panel. Height and Width properties are used to define the area of the canvas, and elements inside are assigned absolute coordinates relative to the area of the parent Canvas. Four attached properties, Canvas.Left, Canvas.Top, Canvas.Right and Canvas.Bottom, allow fine control of object placement within a Canvas, allowing the developer to position and arrange elements precisely on the screen.

ClipToBounds Within a Canvas

Canvas can position child elements at any position on the screen, even at coordinates that are outside of its own defined Height and Width. Furthermore, Canvas is not affected by the size of its children. As a result, it is possible for a child element to overdraw other elements outside the bounding rectangle of the parent Canvas. The default behavior of a Canvas is to allow children to be drawn outside the bounds of the parent Canvas. If this behavior is undesirable, the ClipToBounds property can be set to true. This causes Canvas to clip to its own size. Canvas is the only layout element that allows children to be drawn outside its bounds.

Defining and Using a Canvas

A Canvas can be instantiated simply by using Extensible Application Markup Language (XAML) or code. The following example demonstrates how to use Canvas to absolutely position content. This code produces three 100-pixel squares. The first square is red, and its top-left (x, y) position is specified as (0, 0). The second square is green, and its top-left position is (100, 100), just below and to the right of the first square. The third square is blue, and its top-left position is (50, 50), thus encompassing the lower-right quadrant of the first square and the upper-left quadrant of the second. Because the third square is laid out last, it appears to be on top of the other two squares—that is, the overlapping portions assume the color of the third box.

DockPanel

The DockPanel element uses the DockPanel.Dock attached property as set in child content elements to position content along the edges of a container. When DockPanel.Dock is set to Top or Bottom, it positions child elements above or below each other. When DockPanel.Dock is set to Left or Right, it positions child elements to the left or right of each other. The LastChildFill property determines the position of the final element added as a child of a DockPanel.

You can use DockPanel to position a group of related controls, such as a set of buttons. Alternately, you can use it to create a "paned" UI, similar to that found in Microsoft Outlook.

Sizing to Content

If its Height and Width properties are not specified, DockPanel sizes to its content. The size can increase or decrease to accommodate the size of its child elements. However, when these properties are specified and there is no longer room for the next specified child element, DockPanel does not display that child element or subsequent child elements and does not measure subsequent child elements.

LastChildFill

By default, the last child of a DockPanel element will "fill" the remaining, unallocated space. If this behavior is not desired, set the LastChildFill property to false.

Defining and Using a DockPanel

The following example demonstrates how to partition space using a DockPanel. Five Border elements are added as children of a parent DockPanel. Each uses a different positioning property of a DockPanel to partition space. The final element "fills" the remaining, unallocated space.

Grid

The Grid element merges the functionality of an absolute positioning and tabular data control. A Grid enables you to easily position and style elements. Grid allows you to define flexible row and column groupings, and even provides a mechanism to share sizing information between multiple Grid elements.

How is Grid Different from Table?

Table and Grid share some common functionality, but each is best suited for different scenarios. A Table is designed for use within flow content (see Flow Document Overview for more information on flow content). Grids are best used inside of forms (basically anywhere outside of flow content). Within a FlowDocument, Table supports flow content behaviors like pagination, column reflow, and content selection while a Grid does not. A Grid on the other hand is best used outside of a FlowDocument for many reasons including Grid adds elements based on a row and column index, Table does not. The Grid element allows layering of child content, allowing more than one element to exist within a single "cell." Table does not support layering. Child elements of a Grid can be absolutely positioned relative to the area of their "cell" boundaries. Table does not support this feature. Finally, a Grid is lighter weight than a Table.

Sizing Behavior of Columns and Rows

Columns and rows defined within a Grid can take advantage of Star sizing in order to distribute remaining space proportionally. When Star is selected as the Height or Width of a row or column, that column or row receives a weighted proportion of remaining available space. This is in contrast to Auto, which will distribute space evenly based on the size of the content within a column or row. This value is expressed as * or 2* when using Extensible Application Markup Language (XAML). In the first case, the row or column would receive one times the available space, in the second case, two times, and so on. By combining this technique to proportionally distribute space with a HorizontalAlignment and VerticalAlignment value of Stretch it is possible to partition layout space by percentage of screen space. Grid is the only layout panel that can distribute space in this manner.

Defining and Using a Grid

The following example demonstrates how to build a UI similar to that found on the Run dialog available on the Windows Start menu.

VirtualizingStackPanel

WPF also provides a variation of the StackPanel element that automatically "virtualizes" data-bound child content. In this context, the word virtualize refers to a technique by which a subset of elements are generated from a larger number of data items based upon which items are visible on-screen. It is intensive, both in terms of memory and processor, to generate a large number of UI elements when only a few may be on the screen at a given time. VirtualizingStackPanel (through functionality provided by VirtualizingPanel) calculates visible items and works with the ItemContainerGenerator from an ItemsControl (such as ListBox or ListView) to only create elements for visible items.

The VirtualizingStackPanel element is automatically set as the items host for controls such as the ListBox. When hosting a data bound collection, content is automatically virtualized, as long as the content is within the bounds of a ScrollViewer. This greatly improves performance when hosting many child items.

WrapPanel

WrapPanel is used to position child elements in sequential position from left to right, breaking content to the next line when it reaches the edge of its parent container. Content can be oriented horizontally or vertically. WrapPanel is useful for simple flowing user interface (UI) scenarios. It can also be used to apply uniform sizing to all of its child elements.

The following example demonstrates how to create a WrapPanel to display Button controls that wrap when they reach the edge of their container.

Nested Panel Elements

Panel elements can be nested within each other in order to produce complex layouts. This can prove very useful in situations where one Panel is ideal for a portion of a UI, but may not meet the needs of a different portion of the UI.

There is no practical limit to the amount of nesting that your application can support, however, it is generally best to limit your application to only use those panels that are actually necessary for your desired layout. In many cases, a Grid element can be used instead of nested panels due to its flexibility as a layout container. This can increase performance in your application by keeping unnecessary elements out of the tree.

The following example demonstrates how to create a UI that takes advantage of nested Panel elements in order to achieve a specific layout. In this particular case, a DockPanel element is used to provide UI structure, and nested StackPanel elements, a Grid, and a Canvas are used to position child elements precisely within the parent DockPanel.

Custom Panel Elements

While WPF provides an array of flexible layout controls, custom layout behaviors can also be achieved by overriding the ArrangeOverride and MeasureOverride methods. Custom sizing and positioning can be accomplished by defining new positioning behaviors within these override methods.

The following markup demonstrates how to create a custom Panel element. This new Panel, defined as PlotPanel, supports the positioning of child elements through the use of hard-coded x- and y-coordinates. In this example, a Rectangle element (not shown) is positioned at plot point 50 (x), and 50 (y).

Public Class PlotPanel
Inherits Panel
'Override the default Measure method of Panel.
Protected Overrides Function MeasureOverride(ByVal availableSize As System.Windows.Size) As System.Windows.Size
Dim panelDesiredSize As Size = New Size()
' In our example, we just have one child.
' Report that our panel requires just the size of its only child.
For Each child As UIElement In InternalChildren
child.Measure(availableSize)
panelDesiredSize = child.DesiredSize
Next
Return panelDesiredSize
End Function
Protected Overrides Function ArrangeOverride(ByVal finalSize As System.Windows.Size) As System.Windows.Size
For Each child As UIElement In InternalChildren
Dim x As Double = 50
Dim y As Double = 50
child.Arrange(New Rect(New System.Windows.Point(x, y), child.DesiredSize))
Next
Return finalSize
End Function
End Class

Localization/Globalization Support

WPF supports a number of features that assist in the creation of localizable UI.

All panel elements natively support the FlowDirection property, which can be used to dynamically re-flow content based on a user's locale or language settings. For more information, see FlowDirection.

The SizeToContent property provides a mechanism that enables application developers to anticipate the needs of localized UI. Using the WidthAndHeight value of this property, a parent Window always sizes dynamically to fit content and is not constrained by artificial height or width restrictions.

DockPanel, Grid, and StackPanel are all good choices for localizable UI. Canvas is not a good choice, however, because it positions content absolutely, making it difficult to localize.