3

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>
Phil Wright
  • 22,580
  • 14
  • 83
  • 137
  • 1
    Depending on the effect you're trying to accomplish, an Adorner may be more appropriate for you. The chief cost of using an Adorner is that you have to override `OnRender`, and you've already adopted that cost. :) – Greg D Sep 07 '11 at 23:21

1 Answers1

1

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>
Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • But my RenderPanel is performing custom layout. I guess I would need two controls. My custom panel in the place of WrapPanel above to layout the children in my unique way. Then another custom Panel that overlays the extra graphics using OnRender. – Phil Wright Sep 08 '11 at 00:25
  • @Phil: That was effectively my suggestion - You can merge them into a single control, and just add your canvas into the control's content, too. – Reed Copsey Sep 08 '11 at 00:57