Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use the OnRender event but only render to the control area in WPF?

Background:
I am converting a control from WinForms to WPF. In WinForms I overrode a PictureBox and used the OnPaint event to draw what I needed to that control. That control would handle all the double-buffering and clipping.

I converted the control to WPF and am inheriting from Canvas now. I am overriding the OnRender event and drawing everything to the DrawingContext, but it looks like the DrawingContext allows me to draw past the control onto the rest of the view:

Render example

In the above image the solid dark pink box is the control and the light pink box and green line are drawn at (0, 0), but the blue box is drawn at (0, -100).

In WinForms the PictureBox would clip whatever was not in the control's region.

Also, I found that the blue box does get clipped if the box falls below the control. I assume that is because it does clip below the enclosing Grid, but I'm not sure.

Questions:

  1. What exactly is the DrawingContext doing and why can I draw past my control?
  2. How do I achieve the same functionality with correct clipping in WPF? Do I need to override a different function, draw a different way, or is there some way I can limit the drawing in the OnRender method of my control to the specific region?
  3. Is there a better way to achieve what I am trying to do (arbitrary drawing to a control with correct clipping and double-buffering)?

I tried adding shapes to the Canvas children, but this is extremely slow.

like image 937
Mike Webb Avatar asked Aug 15 '26 04:08

Mike Webb


1 Answers

The issue is related to how Canvas renders stuff. That means its children can be rendered outside its actual region. However you can avoid that default behavior by setting the property ClipToBounds to true:

yourCanvas.ClipToBounds = true;
like image 159
King King Avatar answered Aug 16 '26 19:08

King King