C# WPF Text with links

前端 未结 3 456
萌比男神i
萌比男神i 2021-01-02 12:29

I just found myself a new challenge: Make a Word Processor that is in handling more like the web than plain text. Designing a nice framework for this is what i cant wait to

相关标签:
3条回答
  • 2021-01-02 12:56

    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());
    }
    
    0 讨论(0)
  • 2021-01-02 13:01

    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">
    
    0 讨论(0)
  • 2021-01-02 13:18

    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.

    0 讨论(0)
提交回复
热议问题