Search
Creating Custom Components

Custom Component

To create a custom component simply derive from any of the built-in component classes, ultimately from the ComponentBase class. Usually you will want to override the Draw method in order to render the component and eventually the GetDesiredSize method. A simple custom component is illustrated below:

C#  Copy Code

public class RectangleComponent : ComponentBase
{
    protected override void Draw(MindFusion.Drawing.IGraphics graphics, RenderOptions options)
    {
        graphics.DrawRectangle(Pens.Red, Bounds.X, Bounds.Y, Bounds.Width, Bounds.Height);
    }
}

The above component only renders a red rectangle.

To provide custom component behavior based on the user input, override the OnMouseDown, OnMouseUp, OnMouseMove, OnKeyDown, OnKeyUp and OnKeyPress methods.

Custom Panel

To create a custom container component, you need to derive from the ContainerComponent class and override the ArrangeComponents method and eventually the GetDesiredSize method. From within the ArrangeComponents method you position the individual child components by assigning values to their Bounds property according to their desired size and the arrangement logic of the panel. Below you can find the implementation of a very simple custom panel class, which arranges its children with a constant offset relative to each other.

C#  Copy Code

public class OffsetPanel : ContainerComponent
{
    public override void ArrangeComponents(Rect availableSpace, MindFusion.Drawing.IGraphics graphics)
    {
        double y = 0;
        foreach (ComponentBase component in Components)
        {
            // Calculate the desired size of the component
            var desiredSize = component.GetDesiredSize(availableSpace.Size, graphics);
            component.Bounds = new Rect(y, y, desiredSize.Width, desiredSize.Height);
            component.ArrangeComponents(component.Bounds, graphics);

            y += 2;
        }
    }

    public override Size GetDesiredSize(Size availableSize, MindFusion.Drawing.IGraphics graphics)
    {
        double width = 0;
        double height = 0;

        double y = 0;
        for (int i = 0; i < Components.Count; i++)
        {
            ComponentBase component = Components[i];

            var desiredSize = component.GetDesiredSize(availableSize, graphics);

            width = Math.Max(width, desiredSize.Width + y);
            height = Math.Max(height, desiredSize.Height + y);

            y += 2;
        }

        return new Size(width, height);
    }
}

Using Custom Components in XML

If you want to use custom components in XML you may need to supply a custom ITypeResolver object to the loader. This is especially true if you want to use shortcut names for your components. Consider the above RectangleComponent in the following example:

XML  Copy Code

<Rectangle />

Loading this XML will fail unless you supply an ITypeResolver, which can resolve "Rectangle" to RectangleComponent.