Detect是textblock上的网站地址或电子邮件地址

我有一个TextBlock,其数据来自JSON。 我想如果文本阻止网站地址或电子邮件,文本颜色变为蓝色,用户可以点击(如果电子邮件地址将转到电子邮件应用程序,用户可以直接写入该地址的电子邮件。同时,如果网站地址,它会立即打开网页浏览器)。 XAML:

 

来自http://…/mobileapp/GetPostByCategoryXMLa?term_id = 378的JSON数据示例: JSON

我该如何申请?

我从这里修改了一点答案 ,现在它处理绑定的字符串,搜索网站和电子邮件地址。 一旦它找到一个,它会创建一个超链接,它应该触发电子邮件应用程序或webbrowser。

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 && !string.IsNullOrWhiteSpace(text)) { textBl.Inlines.Clear(); Regex regx = new Regex(@"(http(s)?://[\S]+|www.[\S]+|[\S]+@[\S]+)", RegexOptions.IgnoreCase); Regex isWWW = new Regex(@"(http[s]?://[\S]+|www.[\S]+)"); Regex isEmail = new Regex(@"[\S]+@[\S]+"); foreach (var item in regx.Split(text)) { if (isWWW.IsMatch(item)) { Hyperlink link = new Hyperlink { NavigateUri = new Uri(item.ToLower().StartsWith("http") ? item : $"http://{item}"), Foreground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush }; link.Inlines.Add(new Run { Text = item }); textBl.Inlines.Add(link); } else if (isEmail.IsMatch(item)) { Hyperlink link = new Hyperlink { NavigateUri = new Uri($"mailto:{item}"), Foreground = Application.Current.Resources["SystemControlForegroundAccentBrush"] as SolidColorBrush }; link.Inlines.Add(new Run { Text = item }); textBl.Inlines.Add(link); } else textBl.Inlines.Add(new Run { Text = item }); } } })); } 

和xaml中的代码:

  

你可以在我的Github上找到的工作样本 – 我用你的json测试了它,看起来/效果很好:

在此处输入图像描述