C# WPF 文本链接

8
我刚刚发现自己面临了一个新的挑战:设计一个更像网页而不是纯文本的文字处理器。我迫不及待地想开始设计一个好的框架,但我需要知道GUI方面的可能性(这可能会有很多GUI挑战)。
所以我需要的基本功能是某种控件,可以让我在文本的某些部分上添加点击/鼠标悬停的功能。我对WPF比较陌生,不确定如何实现。是否有人有想法怎样才能实现?是否有示例?是否已经有相关的控件?
谢谢您的帮助!
编辑:
我发现使用richtextbox可以实现。
// Create a FlowDocument to contain content for the RichTextBox.
FlowDocument myFlowDoc = new FlowDocument();

// Add paragraphs to the FlowDocument.

Hyperlink myLink = new Hyperlink();
myLink.Inlines.Add("hyperlink");
myLink.NavigateUri = new Uri("http://www.stackoverflow.com");

// Create a paragraph and add the Run and hyperlink to it.
Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add("check this link out: ");
myParagraph.Inlines.Add(myLink);
myFlowDoc.Blocks.Add(myParagraph);

// Add initial content to the RichTextBox.
richTextBox1.Document = myFlowDoc;

我现在在文本框中得到了一个漂亮的超链接...但是当我点击它时,什么也没有发生。 我错过了什么吗?
3个回答

27
你可以使用Hyperlink类。它是FrameworkContentElement,因此您可以在TextBlock或FlowDocument中或任何其他可以嵌入内容的地方使用它。
<TextBlock>
    <Run>Text</Run>
    <Hyperlink NavigateUri="http://stackoverflow.com">with</Hyperlink>
    <Run>some</Run>
    <Hyperlink NavigateUri="http://google.com">hyperlinks</Hyperlink>
</TextBlock>

你可能希望在编辑器中使用RichTextBox。这将托管一个FlowDocument,其中可以包含超链接等内容。


更新:处理超链接的点击有两种方法。一种是处理RequestNavigate事件。它是一个路由事件,所以你可以将处理程序附加到超链接本身,也可以将其附加到树中更高的元素,如窗口或RichTextBox:

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

另一种方法是使用命令,通过将Hyperlink的Command属性设置为ICommand实现。单击Hyperlink时将调用ICommand上的Executed方法。
如果你想在处理程序中启动浏览器,可以将URI传递给Process.Start
private void RequestNavigateHandler(object sender, RequestNavigateEventArgs e)
{
    Process.Start(e.Uri.ToString());
}

4

请注意,如果您不设置以下属性,RichTextBox中的超链接将被禁用并且无法触发事件。没有IsReadOnly属性时,您需要使用Ctrl + 单击超链接,有了IsReadOnly属性后,它们将在普通左键单击时触发。

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

2

最简单的方法是像这样处理RequestNavigate事件:


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

使用Process.Start启动默认浏览器时可能会出现一些问题,您可能需要搜索更好的实现处理程序的方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接