如何在wpf RichTextBox中为选区添加超链接?
例如,如果我的RichTextBox说:
“发送给Stack Overflow。”
然后我突出显示“溢出”,然后点击一个按钮从中创建一个超链接转到“www.stackoverflow.com”我该如何实现?
另外,我正在尝试从代码中突出显示文本,我无法弄清楚如何。为了突出显示整个RichTextBox,我试过这个,但它没有用:
TextPointer myTextPointer1 = rtb.Document.ContentStart;
TextPointer myTextPointer2 = rtb.Document.ContentEnd;
rtb.Selection.Select(myTextPointer1, myTextPointer2);
答案 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);