我有一个自定义面板,可实现其子级的漂亮自定义布局。我想在面板上添加一些额外的图形,以便覆盖OnRender以添加额外的矩形等。它的工作原理很好,只是OnRender似乎只添加到了背景中。有没有办法让您的OnRender绘图位于子代之上?

示例面板...

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));
    }
}


以这种方式使用

<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>

最佳答案

我将使“ RenderPanel”从画布继承,然后将其放在WrapPanel的顶部,并适当地指定ZIndex。这样的事情应该起作用:

<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>

09-25 20:33