WPF 控件 OnRender 覆盖

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22036332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:01:47  来源:igfitidea点击:

WPF Control OnRender overriding

c#wpf

提问by dmitrynikolaev

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.

只是为了测试如何在 OnRender 中的其他控件之上绘制,我基于 TextBox 创建了自己的控件,并决定覆盖它的 OnRender 方法。但似乎它从未调用过。

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:

我在 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 ?

但是没有迹象表明 OnRender 甚至调用过一次。我缺少什么?在其他控件之上进行自定义绘图的最佳选择是什么?

回答by Sankarann

You should override the default Textboxstyle...

您应该覆盖默认Textbox样式...

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