#1,144 – Geometry in Custom Shape Doesn’t Automatically Scale

If you define a custom Shape by creating some Geometry, the resulting geometry will not automatically scale when shape’s size is changed.

Suppose that we have the following custom shape.

    public class MyShape : Shape
    {
        protected override Geometry DefiningGeometry
        {
            get
            {
                StreamGeometry geom = new StreamGeometry();
                using (StreamGeometryContext ctx = geom.Open())
                {
                    ctx.BeginFigure(
                        new Point(0.0, 0.0),
                        false,
                        false);
                    ctx.LineTo(
                        new Point(50.0, 50.0),
                        true,
                        false);
                }

                return geom;
            }
        }
    }

Placing this control in a StackPanel, it’s size is just large enough to accommodate the geometry.

1144-001

If we explicitly make the shape larger, the underlying geometry stays the same size.

1144-002

Advertisement

#329 – Principles of Layout in WPF

WPF uses a flow-based layout model by default, where child elements are placed in a container and explicitly positioned based on their content.  This is as opposed to coordinate-based layout, where controls are given specific sizes and positions.

Parent containers (deriving from Panel) are responsible for figuring out both the size and position of all of their child controls.

In general, we following the following layout principles in WPF:

  • Don’t give controls a specific size, but let them size to fit their content
  • Don’t give controls a specific location, but let the parent container position them
  • Layout containers can be nested inside of other layout containers