1
votes

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 ?

1
Did you try changing the appearance using ControlTemplate? I feel you need to explore more on the features available on WPF. OnRender is more from the WinForm World - Carbine
You might want to look into adorners for drawing over controls. In case what you're trying to is for validation purposes, have a look at this article. - Adi Lester
Actually I'm from Cocoa World. Some concepts fron WPF very new to me :-( - dmitrynikolaev

1 Answers

3
votes

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