gpt4 book ai didi

windows-phone-7 - 将带有链接的文本绑定(bind)到 RichTextBox

转载 作者:行者123 更新时间:2023-12-04 07:13:26 25 4
gpt4 key购买 nike

我需要将可能包含超链接的文本绑定(bind)到 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),
TargetName = "_blank",
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-phone-7 - 将带有链接的文本绑定(bind)到 RichTextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12959137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com