#1,170 – Custom Panel, part II (Simple Arrangement of Child Elements)

You create a class that derives from Panel in order to create a panel control with custom behavior.  Below, we expand on the earlier example to create a simple panel that stacks its child elements vertically, stretching them to fit the available space.

Here’s what happens:

  • In the Measure phase, we tell each element how big it should be, dividing the vertical space by the # child elements
  • In the Arrange phase, we position the elements
    public class MyPanel : Panel
    {
        protected override Size MeasureOverride(Size availableSize)
        {
            Size childSize = new Size(availableSize.Width, availableSize.Height / InternalChildren.Count);

            foreach (UIElement elem in InternalChildren)
                elem.Measure(childSize);

            return availableSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            double childHeight = finalSize.Height / InternalChildren.Count;
            Size childSize = new Size(finalSize.Width, childHeight);

            double top = 0.0;
            for (int i = 0; i < InternalChildren.Count; i++)
            {
                Rect r = new Rect(new Point(0.0, top), childSize);
                InternalChildren[i].Arrange(r);
                top += childHeight;
            }

            return finalSize;
        }
    }

1170-001

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #1,170 – Custom Panel, part II (Simple Arrangement of Child Elements)

  1. Pingback: Dew Drop – October 1, 2014 (#1867) | Morning Dew

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

%d bloggers like this: