Drawing on top of another control

490 Views Asked by At

Microsoft Word allows you to display grid lines on your document, as shown in this screen shot:

enter image description here

I am trying to create this same effect inside a WPF RichTextBox. What I did is I created my own control called MyRichTextBox which derives from RichTextBox, then I overrode the OnRender method, to simply draw a thick line to test it. The problem is, it looks like my line is being drawn under the text box itself. I can see a piece of it sticking out in the upper left corner. Anyone have any suggestions on how I can draw a line inside the actual text box? Here is my super simple code:

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

There are 1 best solutions below

0
mm8 On

You could define a custom ControlTemplate and override the OnRender method of the RichTextBox's internal ScrollViewer element:

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>