#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">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>

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

1181-001

Advertisements

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

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

  1. Pingback: Dew Drop – October 16, 2014 (#1878) | 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 )

w

Connecting to %s

%d bloggers like this: