#234 – Getting a DrawingVisual Object Rendered in a Window

A class deriving from DrawingVisual that draws one or more 2D objects needs to be hosted in another object in order to render the DrawingVisual object in a window or a page.

You can host the lower level control in either an UIElement or a FrameworkElementUIElement has basic support for layout and is the minimum functionality required in order to host a control within a Window (or a container control).

Here’s an example of overriding FrameworkElement to host our new control.

    public class EllAndRectHost : FrameworkElement
    {
        private EllipseAndRectangle _ellAndRect = new EllipseAndRectangle();

        // EllipseAndRectangle instance is our only visual child
        protected override Visual GetVisualChild(int index)
        {
            return _ellAndRect;
        }

        protected override int VisualChildrenCount
        {
            get
            {
                return 1;
            }
        }
    }

We create a FrameworkElement with one visual child, overriding GetVisualChild and VisualChildrenCount.

Now we can use this new element directly in XAML:

		<local:EllAndRectHost Margin="30"/>

Advertisement

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

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 )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: