I’ve created the simplest possible WPF control – It just overrides OnRender and draws a red rectangle.
However only when setting the Background in XAML to Blue, the control is all blue with no red showing. If Background is not set, the red rectangle shows no problem.
How come the red rectangle is not displayed over the blue background when the background is set?
public class MyWpfControl : Control
{
protected override void OnRender(DrawingContext drawingContext)
{
drawingContext.DrawRectangle(Brushes.Red, null, new Rect(0, 0, 100, 100));
}
}
Because OnRender is done first, then the background is rendered – unless you’re writing a very performance-intensive control, you do not need to override OnRender ever.
Check out Adam Nathan’s book “WPF Unleashed” – it will get you started with the right way of writing controls and give a great introduction to WPF. Leave your Winforms knowledge at the door, things are very different, it’s a separate way of thinking than the Winforms/Win32 approach.