在另一个控件之上绘制

时间:2019-01-19 18:50:03

标签: c# wpf line-drawing

Microsoft Word允许您在文档上显示网格线,如以下屏幕截图所示:

enter image description here

我正在尝试在WPF RichTextBox中创建相同的效果。我要做的是创建自己的控件MyRichTextBox,该控件派生自RichTextBox,然后覆盖了OnRender方法,以简单地绘制粗线对其进行测试。问题是,好像我的线被绘制在文本框下面。我可以看到它的一部分伸出左上角。有人对我如何在实际文本框中画一条线有任何建议吗?这是我的超级简单代码:

public class MyRichTextBox : RichTextBox
{
    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        drawingContext.DrawLine(new Pen(Brushes.LimeGreen, 11.0), 
                new Point(1, 1), new Point(115, 115));
    }
}

1 个答案:

答案 0 :(得分:0)

您可以定义自定义ControlTemplate并覆盖OnRender内部RichTextBox元素的ScrollViewer方法:

public class MyScrollViewer : ScrollViewer
{
    protected override void OnRender(DrawingContext drawingContext)
    {
        base.OnRender(drawingContext);

        drawingContext.DrawLine(new Pen(Brushes.LimeGreen, 11.0),
                new Point(1, 1), new Point(115, 115));
    }
}

XAML:

<RichTextBox>
    <RichTextBox.Resources>
        <SolidColorBrush x:Key="TextBox.Static.Border" Color="#FFABAdB3"/>
        <SolidColorBrush x:Key="TextBox.MouseOver.Border" Color="#FF7EB4EA"/>
        <SolidColorBrush x:Key="TextBox.Focus.Border" Color="#FF569DE5"/>
    </RichTextBox.Resources>
    <RichTextBox.Template>
        <ControlTemplate TargetType="{x:Type TextBoxBase}">
            <Border x:Name="border" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" SnapsToDevicePixels="True">
                <local:MyScrollViewer x:Name="PART_ContentHost" Focusable="false" HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Hidden"/>
            </Border>
            <ControlTemplate.Triggers>
                <Trigger Property="IsEnabled" Value="false">
                    <Setter Property="Opacity" TargetName="border" Value="0.56"/>
                </Trigger>
                <Trigger Property="IsMouseOver" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.MouseOver.Border}"/>
                </Trigger>
                <Trigger Property="IsKeyboardFocused" Value="true">
                    <Setter Property="BorderBrush" TargetName="border" Value="{StaticResource TextBox.Focus.Border}"/>
                </Trigger>
            </ControlTemplate.Triggers>
        </ControlTemplate>
    </RichTextBox.Template>
</RichTextBox>