0

I have a parser XamlReader.Parse(xamlFile) and I need to parse the Hyperlink in it. I have a TextBlock (it supports the Hyperlink) but no idea on how to make the word I want clickable.

Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
beachnugga
  • 35
  • 3
  • No, it doesn't help me... I'm dinamically parsing this XAML... I don't know how to handle the Click event of a parsed element – beachnugga May 26 '14 at 15:02

1 Answers1

0

You could play with the VisualTreeHelper to replace all the matching text with Hyperlinks.

Here is a sample:

void CreateLinks(FrameworkElement fe)
{
    Uri URI = new Uri("http://google.com");

    TextBlock tb = fe as TextBlock;
    if (tb != null)
    {
        string[] tokens = tb.Text.Split();

        tb.Inlines.Clear();

        foreach (string token in tokens)
        {
            if (token == "Click")
            {
                Hyperlink link = new Hyperlink { NavigateUri = URI };
                link.Inlines.Add("Click");
                tb.Inlines.Add(link);
            }
            else
            {
                tb.Inlines.Add(token);
            }

            tb.Inlines.Add(" ");
        }

        tb.Inlines.Remove(tb.Inlines.Last());
    }
    else
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(fe); ++i)
        {
            CreateLinks(VisualTreeHelper.GetChild(fe, i) as FrameworkElement);
        }
    }
}

public MainWindow()
{
    InitializeComponent();

    Loaded += (s, a) =>
        {
            FrameworkElement root = XamlReader.Parse("<Grid xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><TextBlock>Click Click Clock Clack Click</TextBlock></Grid>") as FrameworkElement;

            CreateLinks(root);

            grid.Children.Add(root);
        };
}

Of course you may want to be more subtle for ensuring you keep the exact formatting of your text; with my quick and dirty implementation I'll lose consecutive spaces, and I don't handle the case where the pattern contains spaces.

So you can enhance it by using regex, but as far as WPF is concernend I think you have all the elements to make your own implementation.

Enjoy!

Pragmateek
  • 13,174
  • 9
  • 74
  • 108