#1,178 – Custom Element Based on FrameworkElement

You can create custom user interface elements that derive from FrameworkElement.  Below is a simple example that renders itself as a graphical “X”.  We override the OnRender method (inherited from UIElement) and use the DrawingContext object to create visual content.

    public class MyElement : FrameworkElement
    {
        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));
        }
    }

Using the new element looks like this:

    <Grid>
        <loc:MyElement/>
    </Grid>

Here’s what it looks like at run-time:
1178-001

If we host the Grid as a top-level element in a Window, our element is sized to fit the Grid, which sizes to fit the Window.  Because we render the element using ActualWidth and ActualHeight, it changes size as we resize the window.

1178-002