简体   繁体   English

获取WPF RichTextBox在文本上方绘制水平线

[英]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.) 假设我有一个给定的TextRange range ,恰好在其中包含此文本----------------- (一行)。

I want to draw a real line whenever I see that text (instead of just 15 dashes). 每当我看到该文本时,我都想画一条实线(而不是15个破折号)。

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: 我找到了如何在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. 但这只是在该段落的最后一个Inline之后绘制的。

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)? 如何绘画以便UIElement上没有换行符 (以便覆盖虚线)?

Is this possible with the WPF RichTextBox? WPF RichTextBox是否可能?

Could you use "TextDecorations.Strikethrough" for this. 您可以为此使用“ TextDecorations.Strikethrough”吗?

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. 我认为您必须从段落中删除Inline并将其替换为Line元素。 In this case, you will have to replace Line elements with "-----" on save. 在这种情况下,保存时必须用“ -----”替换Line元素。

    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. 我用一个RTF文档对此进行了测试,该文档的独立段落(<enter>)中带有“ -----”行,而其他段落中具有换行符(<shift-enter>)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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