C# WPF Text with links

前端 未结 3 466
萌比男神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.

    
        Text
        with
        some
        hyperlinks
    
    

    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());
    }
    

提交回复
热议问题