我修改了一下answer from here,現在它處理綁定字符串,搜索網站和電子郵件地址。一旦它找到一個,它創建一個超鏈接,它應該啓動電子郵件應用程序或網頁瀏覽器。
爲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][email protected][\S]+)", RegexOptions.IgnoreCase);
Regex isWWW = new Regex(@"(http[s]?://[\S]+|www.[\S]+)");
Regex isEmail = new Regex(@"[\S][email protected][\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測試,它看起來/工作相當不錯:
Stanislav Kniazev的回答應該有幫助。 http://stackoverflow.com/questions/2092890/add-hyperlink-to-textblock-wpf – HebeleHododo
它不是wpf,但在uwp – Rose
什麼屬性* Deskripsi *?我想你可以看看[這個答案](http://stackoverflow.com/a/27742886/2681948)。 – Romasz