我的代码在每个链接之前添加一个换行符。如何在不添加换行符的情况下添加超链接?这是我的代码:
String link = "http://google.de";
if (Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute))
{
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(link);
Hyperlink hyper = new Hyperlink(paragraph.ContentStart, paragraph.ContentEnd);
hyper.NavigateUri = new Uri(new TextRange(paragraph.ContentStart, paragraph.ContentEnd).Text);
paragraph.Margin = new Thickness(0);
richTextBox1.Document.Blocks.Add(paragraph);
}
换行符完全由段落创建。您可以使用其他Inline元素而不是Block元件来创建一个新的Hyperlink
。代码应该是这样的:
if (Uri.IsWellFormedUriString(link, UriKind.RelativeOrAbsolute)) {
//check if there is any paragraph, if not then add a new one
Paragraph para = null;
if(richTextBox1.Blocks.Count == 0 ||
!(richTextBox1.Blocks.LastBlock is Paragraph)) {
para = new Paragraph();
para.Margin = new Thickness(0);
richTextBox1.Blocks.Add(para);
} else para = richTextBox1.Blocks.LastBlock;
Hyperlink hyper = new Hyperlink(new Run(link));
hyper.NavigateUri = new Uri(link);
//add hyperlink to the last Paragraph
para.Inlines.Add(hyper);
}