通过绑定在TextBlock中创建超链接

我的问题是从文本内容中找到URL并通过数据绑定将其转换为可点击的超链接。

这就是我尝试过的

   

在代码中,

 public class StatusFormatter : IValueConverter { public object Convert(object value, Type targetType, object parameter, string language) { return returnTextWithUrl((String)value); } public static String returnTextWithUrl(String text) { if(text == null) { return null; } MatchCollection mactches = uriFindRegex.Matches(text); foreach (Match match in mactches) { //Need Help here HyperlinkButton hyperlink = new HyperlinkButton(); hyperlink.Content = match.Value; hyperlink.NavigateUri = new Uri(match.Value); text = text.Replace(match.Value, ??); } return text; } } } 

输出应该是这样的

  Click this link - bing - for more info.  

任何帮助?

要执行您想要的操作,您必须使用TextBlock的 Inlines属性,但由于它不是DependencyProperty ,因此它不能成为绑定的目标。 我们将不得不扩展你的TextBlock类,但由于它是密封的,我们将不得不使用其他类。

让我们定义静态类,它将添加适当的内联 – 超链接或运行 ,具体取决于正则表达式匹配。 它可以看起来像这样的例子:

 public static class TextBlockExtension { public static string GetFormattedText(DependencyObject obj) { return (string)obj.GetValue(FormattedTextProperty); } public static void SetFormattedText(DependencyObject obj, string value) { obj.SetValue(FormattedTextProperty, value); } public static readonly DependencyProperty FormattedTextProperty = DependencyProperty.Register("FormattedText", typeof(string), typeof(TextBlockExtension), new PropertyMetadata(string.Empty, (sender, e) => { string text = e.NewValue as string; var textBl = sender as TextBlock; if (textBl != null) { textBl.Inlines.Clear(); Regex regx = new Regex(@"(http://[^\s]+)", RegexOptions.IgnoreCase); var str = regx.Split(text); for (int i = 0; i < str.Length; i++) if (i % 2 == 0) textBl.Inlines.Add(new Run { Text = str[i] }); else { Hyperlink link = new Hyperlink { NavigateUri = new Uri(str[i]), Foreground = Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush }; link.Inlines.Add(new Run { Text = str[i] }); textBl.Inlines.Add(link); } } })); } 

然后在XAML中我们就像这样使用它:

  

在将一些文字写入我的财产后:

 private void firstBtn_Click(object sender, RoutedEventArgs e) { MyText = @"Simple text with http://mywebsite.com link"; } 

我可以看到这样的结果:

SampleLink

您不能将超链接对象放在String中。 相反,您需要从转换器返回包含内联的Span。 纯文本将是Run对象,链接将是Hyperlink对象。

  public static Span returnTextWithUrl(String text) { if(text == null) { return null; } var span = new Span(); MatchCollection mactches = uriFindRegex.Matches(text); int lastIndex = 0; foreach (Match match in mactches) { var run = new Run(text.Substring(lastIndex, match.Index - lastIndex)); span.Inlines.Add(run); lastIndex = match.Index + match.Length; var hyperlink = new Hyperlink(); hyperlink.Content = match.Value; hyperlink.NavigateUri = new Uri(match.Value); span.Inlines.Add(hyperlink); } span.Inlines.Add(new Run(text.Substring(lastIndex))); return span; }