简体   繁体   中英

Get a WPF RichTextBox to draw a horizontal line over text

Say I have a given TextRange range that happens to have this text in it ----------------- (On its own line.)

I want to draw a real line whenever I see that text (instead of just 15 dashes).

But, I need to leave the dashes there for when I save it (and when other, plain text viewers load it).

I found how I can draw a line in the RichTextBox:

var line = new Line {X1 = 10, X2 = 200, Y1 = 5, Y2 = 5, 
var paragraph = (Paragraph) MyRichTextBox.Document.Blocks.FirstBlock;
paragraph.Inlines.Add(line);

But this just draw after the last Inline in the paragraph.

So, my question is:

How can I draw so that my UIElement does not have text wrapping on (so that I can cover the dashes)?

Is this possible with the WPF RichTextBox?

Could you use "TextDecorations.Strikethrough" for this.

TextRange range = new TextRange(RichTextBox.Selection.Start, RichTextBox.Selection.End);

TextDecorationCollection tdc = (TextDecorationCollection)RichTextBox.Selection.GetPropertyValue(Inline.TextDecorationsProperty);
if (!tdc.Equals(TextDecorations.Strikethrough))
{
    tdc = TextDecorations.Strikethrough;
}
range.ApplyPropertyValue(Inline.TextDecorationsProperty, tdc);

I think you have to remove the Inline from within the paragraph and replace it with a Line element. In this case, you will have to replace Line elements with "-----" on save.

    private void FindHRules()
    {
        foreach (Paragraph block in rtf.Document.Blocks.OfType<Paragraph>())
        {
            var inlines = block.Inlines.ToList();
            for(int i = 0; i<inlines.Count; i++)
            {
                var inline = inlines[i];
                TextRange r = new TextRange(inline.ContentStart, inline.ContentEnd);
                if (r.Text.StartsWith("--"))
                {
                    Line l = new Line { Stretch = Stretch.Fill, Stroke = Brushes.DarkBlue, X2 = 1 };
                    block.Inlines.InsertAfter(inline, new InlineUIContainer(l));
                    block.Inlines.Remove(inline);
                }
            }
        }
    }

I tested this with a RTF doc that had the "-----" lines in stand-alone paragraphs (<enter>) and line breaks (<shift-enter>) within other paragraphs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM