I'd like to insert a WPF Hyperlink element into a FlowDocument programmatically.
The objective is to create a toolbar button that would take a run of text within a RichTextBox and replace it with a Hyperlink. It's the same sort of interface you see on the web for creating hyperlinks on wikis or in blogs (or on StackOverflow).
I can find the TextRange of the selected text like this:
TextRange tr = new TextRange(
MyRichTextBox.Selection.Start,
MyRichTextBox.Selection.End);
And I'm attempting to stuff the Hyperlink Xaml into the TextRange like so:
string rawXaml = "<Hyperlink xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" NavigateUri=\"http://www.google.com/\">Google Home Page</Hyperlink>";
using(MemoryStream stream = new MemoryStream())
{
StreamWriter writer = new StreamWriter(stream);
writer.Write(rawXaml);
writer.Flush();
stream.Position = 0;
if (tr.CanLoad(DataFormats.Xaml))
{
tr.Load(stream, DataFormats.Xaml);
}
}
But I still seem to get plain text pasted into the RichTextBox.
What am I doing wrong here? Are there better ways to accomplish what I'm trying to do?
Use the constructor for Hyperlink that takes in a TextPointer:
Or, change the text first and then use the one that takes two TextPointers:
Edit: If you want to use TextRange.Load, try wrapping the Hyperlink in a Span:
I'm not sure why this works when a plain Hyperlink doesn't, but it's closer to what gets returned by TextRange.Save.