C# WPF Text with links

你说的曾经没有我的故事 提交于 2019-11-30 14:28:23

You can use the Hyperlink class. It's a FrameworkContentElement, so you can use it in a TextBlock or FlowDocument or anywhere else you can embed content.

<TextBlock>
    <Run>Text</Run>
    <Hyperlink NavigateUri="http://stackoverflow.com">with</Hyperlink>
    <Run>some</Run>
    <Hyperlink NavigateUri="http://google.com">hyperlinks</Hyperlink>
</TextBlock>

You may want to look at using a RichTextBox as part of your editor. This will host a FlowDocument, which can contain content such as Hyperlinks.


Update: There are two ways to handle clicks on the Hyperlink. One is to handle the RequestNavigate event. It is a Routed Event, so you can either attach a handler to the Hyperlink itself or you can attach one to an element higher in the tree such as the Window or the RichTextBox:

// On a specific Hyperlink
myLink.RequestNavigate +=
    new RequestNavigateEventHandler(RequestNavigateHandler);
// To handle all Hyperlinks in the RichTextBox
richTextBox1.AddHandler(Hyperlink.RequestNavigateEvent,
    new RequestNavigateEventHandler(RequestNavigateHandler));

The other way is to use commanding by setting the Command property on the Hyperlink to an ICommand implementation. The Executed method on the ICommand will be called when the Hyperlink is clicked.

If you want to launch a browser in the handler, you can pass the URI to Process.Start:

private void RequestNavigateHandler(object sender, RequestNavigateEventArgs e)
{
    Process.Start(e.Uri.ToString());
}

Note you also need to set the following properties on your RichTextBox or the hyperlinks will be disabled and won't fire off events. Without IsReadOnly you need to Ctrl-click the hyperlinks, with IsReadOnly they fire with a regular left-click.

<RichTextBox
    IsDocumentEnabled="True"
    IsReadOnly="True">

The simplest way is to handle RequestNavigate event like this:


...
myLink.RequestNavigate += HandleRequestNavigate;
...

private void HandleRequestNavigate(object sender, RoutedEventArgs e)
{
   var link = (Hyperlink)sender;
   var uri = link.NavigateUri.ToString();
   Process.Start(uri);
   e.Handled = true;
}

There are some issues with starting a default browser by passing url to the Process.Start and you might want to google for a better way to implement the handler.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!