我有一个TextBlock,其数据来自JSON。我想如果文本阻止网站地址或电子邮件,文本颜色变为蓝色,用户可以点击(如果电子邮件地址将转到电子邮件应用程序,用户可以直接写入该地址的电子邮件。同时,如果网站地址,它会立即打开网页浏览器)。 XAML:
<TextBlock x:Name="DetailDeskripsi" Width="290" Text="{Binding Deskripsi}" VerticalAlignment="Top" HorizontalAlignment="Left" Height="auto" TextWrapping="Wrap" FontSize="15" TextAlignment="Justify" Foreground="#FFCA6402"/>
来自http://.../mobileapp/GetPostByCategoryXMLa?term_id=378的JSON数据示例:
如何申请?
答案 0 :(得分:0)
我稍微修改了answer from here,现在它处理绑定的字符串,搜索网站和电子邮件地址。一旦找到它,它会创建一个超链接,它应该触发电子邮件应用程序或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中的代码:
<TextBlock extension:TextBlockExtension.FormattedText="{x:Bind TextToFormat, Mode=OneWay}" FontSize="15" Margin="10" TextWrapping="WrapWholeWords"/>
The working sample you will find at my Github - 我已经用你的json测试了它看起来/效果很好: