简体   繁体   中英

WPF RichTextBox - Add a hyperlink without line break?

My code adds a line break before each link. How can i add hyperlinks without adding line breaks? This is my code:

        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);
        }

The linebreaks are exactly created by the paragraph. You can just create a new Hyperlink using some other Inline element not Block element. The code should be like this:

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);            
}

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