在wpf RichTextBox&中超链接所选文本从代码中设置选择

时间:2012-05-31 18:42:23

标签: c# wpf hyperlink richtextbox

如何在wpf RichTextBox中为选区添加超链接?

例如,如果我的RichTextBox说:

“发送给Stack Overflow。”

然后我突出显示“溢出”,然后点击一个按钮从中创建一个超链接转到“www.stackoverflow.com”我该如何实现?

另外,我正在尝试从代码中突出显示文本,我无法弄清楚如何。为了突出显示整个RichTextBox,我试过这个,但它没有用:

    TextPointer myTextPointer1 = rtb.Document.ContentStart;
    TextPointer myTextPointer2 = rtb.Document.ContentEnd;

    rtb.Selection.Select(myTextPointer1, myTextPointer2);

1 个答案:

答案 0 :(得分:1)

    TextSelection ts = rtb.Selection;
    TextPointer start = ts.Start;
    TextPointer end = ts.End;

    TextRange before = new TextRange(rtb.Document.ContentStart, start);
    TextRange after = new TextRange(end, rtb.Document.ContentEnd);
    TextRange linker = new TextRange(start, end);

    Paragraph myParagraph = new Paragraph();
    myParagraph.Inlines.Clear();
    myParagraph.Inlines.Add(before.Text);

    Hyperlink hyperLink = new Hyperlink();
    hyperLink.Inlines.Add(ts.Text);

    hyperLink.Click += new RoutedEventHandler(hyperLink_Click);
    myParagraph.Inlines.Add(hyperLink);
    myParagraph.Inlines.Add(after.Text);

    rtb.Document.Blocks.Clear();

    rtb.Document.Blocks.Add(myParagraph);