#1,181 – Custom Element Indicates Desired Size in MeasureOverride

By default, a custom element deriving from FrameworkElement has no desired size.  Most elements should override MeasureOverride as a way of indicating what their desired size should be.  This would typically be based on the control’s content, but also might be some minimum size.

Below, we have a custom element that indicates that it has a minimum size of 20 x 20.

    public class MyFrameworkElement : FrameworkElement
        protected override Size MeasureOverride(Size availableSize)
            return new Size(20.0, 20.0);

        protected override void OnRender(DrawingContext dc)
            dc.DrawLine(new Pen(Brushes.Blue, 2.0),
                new Point(0.0, 0.0),
                new Point(ActualWidth, ActualHeight));
            dc.DrawLine(new Pen(Brushes.Green, 2.0),
                new Point(ActualWidth, 0.0),
                new Point(0.0, ActualHeight));

We can still specify a desired size when consuming the element, overriding the default size.

    <Grid ShowGridLines="True">

        <loc:MyFrameworkElement HorizontalAlignment="Center"
        <loc:MyFrameworkElement Grid.Row="1" Margin="20,10"/>