My answer is based on @BionicCode's answer, which I wanted to extend with the event handler code, which I had some difficulties to get it working.
<RichTextBox IsDocumentEnabled="True" IsReadOnly="True">
<FlowDocument>
<Paragraph>
<Run Text="Some editable text" />
<Hyperlink x:Name="DuckduckgoHyperlink"
NavigateUri="https://duckduckgo.com">
DuckDuckGo
</Hyperlink>
</Paragraph>
</FlowDocument>
</RichTextBox>
I changed his code slightly:
- I wanted the
RichTextBox
to be readonly. When the RichTextBox
is readonly, it is not necessary to put the HyperLink
into a TextBlock
. However, using TextBlock
in a RichTextBlock
where the user can make changes is a great suggestion.
- In my programming style, code related stuff belongs in the code behind file. Event handlers are code and I prefer to even add the event handler to its control from code behind. To do that, it is enough to give the
Hyperlink
a name.
Code behind
I needed to display some rich text with links in a HelpWindow
:
public HelpWindow() {
InitializeComponent();
DuckduckgoHyperlink.RequestNavigate += Hyperlink_RequestNavigate;
}
private void Hyperlink_RequestNavigate(object sender,
RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) {
UseShellExecute = true,
});
e.Handled = true;
}
Note that the same event handler can be used by any HyperLink
. Another solution would be not to define the URL in XAML but hard code it in the event handler, in which case each HyperLink
needs its own event handler.
In various Stackoverflow answers I have seen the code:
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
Which resulted in the error message:
System.ComponentModel.Win32Exception: 'An error occurred trying to start process 'https://duckduckgo.com/' with working directory '...\bin\Debug\net6.0-windows'. The system cannot find the file specified.'