3.5 Features: Enabled hyperlinks in RichTextBox


hmmm… that was one often requested feature. So to enable hyperlinks in RichTextBox all that is needed is to set the property IsDocumentEnabled on the RichTextBox.


Type the following in XamlPadX and you have the hyperlink navigation working.


<RichTextBox IsDocumentEnabled=True xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml>


        <FlowDocument>


               <Paragraph>


                       <Hyperlink NavigateUri=http://club.live.com>Live Games</Hyperlink>


               </Paragraph>


        </FlowDocument>


</RichTextBox >


A couple of things to notice here:


1> The Navigation is possible only on a Ctrl Click operation


2> There is no tooltip to indicate that navigation is possible. You could add this to the Hyperlink. A simpler alternative is to just subclass the Hyperlink and add the tooltip in the constructor


    public class MyHyperlink:Hyperlink


    {


        public MyHyperlink()


        {


            this.ToolTip = “Ctrl Click to Open”;


            this.RequestNavigate += new RequestNavigateEventHandler(MyHyperlink_RequestNavigate);


        }


 


        void MyHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)


        {


                NavigationWindow window = new NavigationWindow();


                window.Source = e.Uri;


                window.Show();


        }


    }



So why the event handler… In the case where the RichTextBox is hosted in a NavigationWindow thats not required. However, if the RichTextBox in not in a navigation control such as Window, then we need to explicitly navigate to the link.


 


Share this post

 

Comments (3)

  1. Why subclass?  Why not use templates/styles to do this?

  2. William, yeah you can definitely use templates and styles. However, if you are having some code behind in the case of events a subclass works better.