C# – WPF Control OnRender overriding

cwpf

Just to test how to draw on top of other controls within OnRender, I've created my own control based on TextBox, and decide to override it's OnRender method. But seems it never called.

Here is simple class I've got:

public class MyTextBox : TextBox
{
    protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
    {
        Console.WriteLine("OnRender");
        //base.OnRender(drawingContext);
        Rect bounds = new Rect(0, 0, 100, 100);
        Brush brush = new SolidColorBrush(Colors.Yellow);
        drawingContext.DrawRectangle(brush, null, bounds);
    }
}

I declared this class in XAML:

<local:MyTextBox Height="118" Margin="10,300,10,10" Text="TextBox" VerticalAlignment="Bottom" AcceptsReturn="True" Padding="0,0,200,0" FontSize="18" TextWrapping="Wrap" />

But there's no signs that OnRender called even one time. What's I'm missing? What the best option to do custom drawing on top of other control ?

Best Answer

You should override the default Textbox style...

public class MyTextBox : TextBox
{

    public MyTextBox()
    {
        DefaultStyleKey = typeof (MyTextBox);
    }

    protected override void OnRender(System.Windows.Media.DrawingContext drawingContext)
    {
         Console.WriteLine("OnRender");
         //base.OnRender(drawingContext);
         Rect bounds = new Rect(0, 0, 100, 100);
         Brush brush = new SolidColorBrush(Colors.Yellow);
         drawingContext.DrawRectangle(brush, null, bounds);
    }
}