将超链接添加到 textblock wpf

问题描述:

您好,我在数据库中有一些文本,如下所示:

Greetings, I have some text in a db and it is as follows:

Lorem ipsum dolor 坐 amet,consectetur adipiscing 精英.杜伊斯Tellus nisl、venenatis et pharetra ac、tempor sed sapien.整数pellentesque blandit velit,在 tempus urna semper 坐 amet.杜伊斯mollis, libero ut consectetur interdum, massatellus posuere nisi, 欧盟aliquet elit lacus neerat.Praesent commodo quam.**[一种href='http://somesite.com']某个网站[/a]**在 nisi 的悬念massa molestie gravida feugiat ac sem.Phasellus ac mauris ipsum, vel欧德欧

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis tellus nisl, venenatis et pharetra ac, tempor sed sapien. Integer pellentesque blandit velit, in tempus urna semper sit amet. Duis mollis, libero ut consectetur interdum, massa tellus posuere nisi, eu aliquet elit lacus nec erat. Praesent a commodo quam. **[a href='http://somesite.com']some site[/a]**Suspendisse at nisi sit amet massa molestie gravida feugiat ac sem. Phasellus ac mauris ipsum, vel auctor odio

我的问题是:如何在 TextBlock 中显示 Hyperlink?我不想为此使用 webBrowser 控件.我也不想使用这个控件:http://www.codeproject.com/KB/WPF/htmltextblock.aspx

My question is: How can I display a Hyperlink in a TextBlock? I don't want to use a webBrowser control for this purpose. I don't want to use this control either: http://www.codeproject.com/KB/WPF/htmltextblock.aspx also

在这种情况下,您可以将 Regex 与值转换器一起使用.

You can use Regex with a value converter in such situation.

将此用于您的要求(来自此处的原始想法):

Use this for your requirements (original idea from here):

    private Regex regex = 
        new Regex(@"[as+href='(?<link>[^']+)'](?<text>.*?)[/a]",
        RegexOptions.Compiled);

这将匹配包含链接的字符串中的所有链接,并为每个匹配创建 2 个命名组:linktext

This will match all links in your string containing links, and make 2 named groups for each match : link and text

现在您可以遍历所有匹配项.每场比赛都会给你一个

Now you can iterate through all the matches. Each match will give you a

    foreach (Match match in regex.Matches(stringContainingLinks))
    { 
        string link    = match.Groups["link"].Value;
        int link_start = match.Groups["link"].Index;
        int link_end   = match.Groups["link"].Index + link.Length;

        string text    = match.Groups["text"].Value;
        int text_start = match.Groups["text"].Index;
        int text_end   = match.Groups["text"].Index + text.Length;

        // do whatever you want with stringContainingLinks.
        // In particular, remove whole `match` ie [a href='...']...[/a]
        // and instead put HyperLink with `NavigateUri = link` and
        // `Inlines.Add(text)` 
        // See the answer by Stanislav Kniazev for how to do this
    }

注意:在您的自定义 ConvertToHyperlinkedText 值转换器中使用此逻辑.

Note : use this logic in your custom ConvertToHyperlinkedText value converter.