windows-phone-7 – 绑定带有RichTextBox链接的文本
发布时间:2020-12-14 01:47:02 所属栏目:Windows 来源:网络整理
导读:我需要绑定可能包含RichTextBox超链接的文本,以便它可以将文本显示为普通文本,链接显示为超链接. 例如,我有以下文字: Join us on social networkshttp://www.facebook.com/ 我希望文本中的链接是超链接,因此RichTextBox中的结果将如下所示: 加入我们的社交
我需要绑定可能包含RichTextBox超链接的文本,以便它可以将文本显示为普通文本,链接显示为超链接.
例如,我有以下文字: Join us on social networks http://www.facebook.com/ 我希望文本中的链接是超链接,因此RichTextBox中的结果将如下所示: 加入我们的社交网络 http://www.facebook.com/
我实现了我需要的东西
using System; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Text.RegularExpressions; using System.Windows.Media; namespace NazarGrynko.UI.Controls { public class MyRichTextBox : RichTextBox { private const string UrlPattern = @"(http|ftp|https)://[w-_]+(.[w-_]+)+([w-.,@?^=%&:/~+#]*[w-@?^=%&/~+#])?"; public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text",typeof (string),typeof(MyRichTextBox ),new PropertyMetadata(default(string),TextPropertyChanged)); public string Text { get { return (string) GetValue(TextProperty); } set { SetValue(TextProperty,value); } } private static void TextPropertyChanged(DependencyObject dependencyObject,DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var richTextBox = (MyRichTextBox)dependencyObject; var text = (string) dependencyPropertyChangedEventArgs.NewValue; int textPosition = 0; var paragraph = new Paragraph(); var urlMatches = Regex.Matches(text,UrlPattern); foreach (Match urlMatch in urlMatches) { int urlOccurrenceIndex = text.IndexOf(urlMatch.Value,textPosition,StringComparison.Ordinal); if (urlOccurrenceIndex == 0) { var hyperlink = new Hyperlink { NavigateUri = new Uri(urlMatch.Value),TargetName = "_blank",Foreground = Application.Current.Resources["PhoneAccentBrush"] as Brush }; hyperlink.Inlines.Add(urlMatch.Value); paragraph.Inlines.Add(hyperlink); textPosition += urlMatch.Value.Length; } else { paragraph.Inlines.Add(text.Substring(textPosition,urlOccurrenceIndex - textPosition)); textPosition += urlOccurrenceIndex - textPosition; var hyperlink = new Hyperlink { NavigateUri = new Uri(urlMatch.Value),Foreground = Application.Current.Resources["PhoneAccentBrush"] as Brush }; hyperlink.Inlines.Add(urlMatch.Value); paragraph.Inlines.Add(hyperlink); textPosition += urlMatch.Value.Length; } } if (urlMatches.Count == 0) { paragraph.Inlines.Add(text); } richTextBox.Blocks.Add(paragraph); } } } 使用示例: <MyRichTextBox Text="{Binding Message}"/> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- windows – 在NTFS卷上快速查找一组文件名,最好是通过其MFT
- 使用therubyracer在Windows机器上安装ruby gem less-rails
- 作为Windows服务运行时,Tomcat 7控制台和/或托盘图标不显示
- windows-8 – 是否可以在Windows RT上编程
- windows-7 – 卡巴斯基处理错误Explorer.exe(回收站)
- Windows – 64位大型mallocs
- windows – 批处理文件中的“%1”和“%2”是什么?
- windows-server-2008 – 如何在将Windows 2008 Server连接到
- 无法在Windows 10上的MySQL 8.x中设置lower_case_table_nam
- 如何从批处理文件中将行号添加到文本文件中(Windows)