#1,189 – MeasureOverride Input and Output

The MeasureOverride method in FrameworkElement takes as input a Size and then returns a Size.  These parameters are intended to be used as follows:

  • Input Size – during layout, this is how much room is available for the element to be rendered
  • Output Size – this is how much room the element says that it needs

For example, below we have a custom element that draws a big “X” using all of the available space.  (When rendering, it uses ActualWidth and ActualHeight).  Because it will use as much room as it is given, MeasureOverrides return value is all of the available space.

    public class MyElement : FrameworkElement
    {
        protected override Size MeasureOverride(Size availableSize)
        {
            Size sizeIWillNeed = availableSize;

            return sizeIWillNeed;
        }

        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));
        }
    }