How to create a Custom Layout Panel in WPF
WPF already ships with a rich set of layout panels. Each of them fits to solve a particular problem.
- Canvas - To arrange elements by X,Y coordinates.
- Grid - To arrange elements based on rows and columns.
- StackPanel - To stack elements horizontally or vertically.
- DockPanel - To dock elements to a particular side.
- WrapPanel - To stack elements and automatically begin a new row.
But sometimes none of the included layout panels helps you to arrange child elements in the way you like it. In this case its easy to write your own layout panel. All you need to do is to create a new class that derives from Panel . There are two methods to override:
- MeasureOverride - to determine the required size of the panel according to the desired size of the child elements and the available space.
- ArrangeOverride - to arrange the elements in the finally available space. The final size can be smaller than the requested.
public class MySimplePanel : Panel
{
// Make the panel as big as the biggest element
protected override Size MeasureOverride(Size availableSize)
{
Size maxSize = new Size();
foreach( UIElement child in InternalChildern)
{
child.Measure( availableSize );
maxSize.Height = Math.Max( child.DesiredSize.Height, maxSize.Height);
maxSize.Width= Math.Max( child.DesiredSize.Width, maxSize.Width);
}
}
// Arrange the child elements to their final position
protected override Size ArrangeOverride(Size finalSize)
{
foreach( UIElement child in InternalChildern)
{
child.Arrange( new Rect( finalSize ) );
}
}
}
Popular Custom Panels
Here are some popular custom panels on the internet:
Last modified: 2009-08-11 01:07:26
Copyright (c) by Christian Moser, 2011.
Comments on this article
Show all comments
|
Venu | |
|
Commented on 29.June 2009 |
Good example..
|
|
|
|
Ido Ran | |
|
Commented on 10.August 2009 |
Not so good example - according to Microsoft http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.measureoverride.aspx
you should call Measure on each of the children before getting their DesiredSize - you forgot to do that.
|
|
|
|
Christian Moser | |
|
Commented on 11.August 2009 |
Hi Ido,
thanks for the feedback. I really forgot to call Measure(). I corrected it in the example.
|
|
|
|
Chris | |
|
Commented on 7.April 2010 |
You're also not returning the values in the methods. This wont compile
|
|
|
|
Rajesh | |
|
Commented on 31.August 2010 |
Very nice article
|
|
|
|
vishnuvardhan | |
|
Commented on 6.September 2010 |
some more clear
|
|
|
|
Steve | |
|
Commented on 18.November 2010 |
As someone already said, you aren't returning the values from methods and "Children" is spelled incorrectly in "InternalChildern" [sic].
|
|
|
|