#1,170 – Custom Panel, part II (Simple Arrangement of Child Elements)
October 1, 2014 1 Comment
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; } }
Pingback: Dew Drop – October 1, 2014 (#1867) | Morning Dew