Welcome to MSDN Blogs Sign in | Join | Help

Lester's WPF blog


Simple, easy & beautiful

News

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

 

Posted: Thursday, August 09, 2007 4:43 PM by llester

Comments

William Kempf said:

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

# August 9, 2007 2:22 PM

llester said:

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.

# August 9, 2007 2:32 PM
New Comments to this post are disabled
Page view tracker