Microsoft Dot Net Master

Microsoft Dot Net Master
Microsoft Dot Net Master

Saturday, July 7, 2012

How to create a Custom Layout Panel in WPF

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:

No comments:

Post a Comment