代码之家  ›  专栏  ›  技术社区  ›  Len Tango Ben

C#带链接的WPF文本

  •  7
  • Len Tango Ben  · 技术社区  · 15 年前

    我刚刚发现了一个新的挑战: 使文字处理器在处理方面更像网络而不是纯文本。 为此设计一个很好的框架是我迫不及待要开始的,但我确实需要知道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 回复  |  直到 8 年前
        1
  •  24
  •   Quartermeister    15 年前

    你可以用 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


    更新:有两种方法来处理点击超链接。一是处理问题 RequestNavigate 事件。它是一个 Routed Event

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

    另一种方法是使用 commanding 通过设置 Command ICommand 实施。单击超链接时,将调用ICommand上已执行的方法。

    Process.Start :

    private void RequestNavigateHandler(object sender, RequestNavigateEventArgs e)
    {
        Process.Start(e.Uri.ToString());
    }
    
        2
  •  4
  •   Ray Ackley    12 年前

    <RichTextBox
        IsDocumentEnabled="True"
        IsReadOnly="True">
    
        3
  •  1
  •   Konstantin Oznobihin    15 年前

    最简单的方法是处理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;
    }
    
    

    通过向进程传递url来启动默认浏览器时存在一些问题。启动后,您可能希望通过google搜索更好的方法来实现处理程序。