Question

I have a custom panel that implements a nice custom layout of its children. I want to add some extra graphics to the panel and so override OnRender to add extra rectangles etc. It works great except the OnRender only seems to add to the background. Is there a way to get your OnRender drawing to be on top of the children?

An example Panel...

public class RenderPanel : WrapPanel
{
    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);
        drawingContext.DrawRectangle(Brushes.Red, 
                                     new Pen(Brushes.Black, 2), 
                                     new Rect(0, 0, 100, 100));
    }
}

...used in this way...

<Grid>
    <my:RenderPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
        <Button Margin="10" Content="Hello"/>
        <Button Margin="10" Content="Hello"/>
        <Button Margin="10" Content="Hello"/>
        <Button Margin="10" Content="Hello"/>
    </my:RenderPanel>
</Grid>
Was it helpful?

Solution

I would make your "RenderPanel" inherit from canvas, and then lay it on top of the WrapPanel and specify the ZIndex as appropriate. Something like this should work:

<Grid>
    <WrapPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Canvas.ZIndex="0">
        <Button Margin="10" Content="Hello"/>
        <Button Margin="10" Content="Hello"/>
        <Button Margin="10" Content="Hello"/>
        <Button Margin="10" Content="Hello"/>
    </WrapPanel>
    <my:RenderPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Canvas.ZIndex="1" />
</Grid>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top