0
votes

I want to insert a hyperlink with displayText into a richtextbox at the current caret position, I am displaying a popup window for the user to enter the linkURL and the linkText when the user clicks on the Ok button the hyperlink with the display text should be inserted at the current caret position in the RichTextBox.

Thanks in advance.

1

1 Answers

1
votes

Test This Code

        Hyperlink link = new Hyperlink();
        link.IsEnabled = true;
        link.Inlines.Add(" Microsoft ");
        link.NavigateUri = new Uri("http://www.microsoft.com");

        var allRang = new TextRange(Rich.Document.ContentStart,Rich.Document.ContentEnd);
        if (allRang.Start.Parent is Run)
        {
            var run = allRang.Start.Parent as Run;
            var runBefore =
                           new Run(new TextRange(run.ContentStart, Rich.CaretPosition).Text);
            var runAfter =
                           new Run(new TextRange(Rich.CaretPosition, run.ContentEnd).Text);

            if (allRang.Start.Paragraph != null)
            {
                allRang.Start.Paragraph.Inlines.Add(runBefore);
                allRang.Start.Paragraph.Inlines.Add(link);

                allRang.Start.Paragraph.Inlines.Add(runAfter);
                allRang.Start.Paragraph.Inlines.Remove(run);
            }
        }