Search code examples
c#wpfframeworkelement

Added Thumb not rendered


I want to implement my own control derived from FrameworkElement, but the added child elements are not rendered.

I have no idea why.

public class RangeSelection : FrameworkElement
{
    private Thumb thumb = null;

    #region Construction / Destruction

    public RangeSelection()
    {
        this.thumb = new Thumb();
        this.thumb.Width    = 32.0;
        this.thumb.Height   = 32.0;
        this.AddVisualChild(this.thumb);

    }

    #endregion

    protected override Size MeasureOverride(Size availableSize)
    {
        this.thumb.Measure(availableSize);
        return new Size(64.0, 64.0);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        this.thumb.Arrange(new Rect(0, 0, 64.0, 64.0));
        return base.ArrangeOverride(finalSize);
    }
}

Solution

  • You need to override VisualChildrenCount property and GetVisualChild method. Something like this:

    protected override int VisualChildrenCount
    {
        get { return thumb == null ? 0 : 1; }
    }
    
    protected override Visual GetVisualChild(int index)
    {
        if (_child == null)
        {
            throw new ArgumentOutOfRangeException();
        }
    
        return _child;
    }
    

    In case you want more child elements, you should use some kind of collection to store child elements and then you will return collection's count or appropriate element of collection.