#1,171 – Custom Panel, part III (Using DesiredSize)

When creating a custom panel and overriding the measure and arrange methods, your custom panel can make use of a child element’s DesiredSize property when deciding what size to make each child and where to arrange them.

The code below arranges child elements vertically, like a vertical StackPanel, stretching each child to fit the panel’s full width, but using each child element’s DesiredSize.Height.

    public class MyPanel : Panel
        protected override Size MeasureOverride(Size availableSize)
            // Tell child they have as much height as they want
            Size childSize = new Size(availableSize.Width, double.PositiveInfinity);

            // Calling Measure causes each child to set its DesiredSize property
            foreach (UIElement elem in InternalChildren)

            return availableSize;

        protected override Size ArrangeOverride(Size finalSize)
            Size childSize;

            double top = 0.0;
            for (int i = 0; i < InternalChildren.Count; i++)
                // We force each child to full width, but let it
                // be at desired height
                childSize = new Size(finalSize.Width, InternalChildren[i].DesiredSize.Height);
                Rect r = new Rect(new Point(0.0, top), childSize);
                top += childSize.Height;

            return finalSize;

We can use the panel as follows:

    <loc:MyPanel Margin="5" Background="LightGray">
        <Label Content="I'm child #1"
               Background="Thistle" />
        <Label Content="I'm child #2"
               Background="Lavender" />
        <Label Content="Third kid"
               Background="Honeydew" />

The panel at runtime looks like:


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: