添加到textblock wpf的超链接

nia*_*iao 32 html wpf textblock hyperlink

问候,我在db中有一些文本,它如下:

Lorem ipsum dolor坐下来,精致的adipistur elit.Duis tellus nisl,venenatis et pharetra ac,tempor sed sapien.整齐的pellentesque blandit velit,在tempus urna semper坐下来.Duis mollis,libero ut consectetur interdum,massa tellus posuere nisi,eu aliquet elit lacus nec erat.赞美商品.**[a href =' http ://somesite.com']某个网站[/ a]**在新西兰的Suspendisse坐在amet massa molestie gravida feugiat ac sem.Phasellus ac mauris ipsum,vel auctor odio

我的问题是:我怎样才能显示Hyperlink一个TextBlock?我不想为此目的使用webBrowser控件.我不想使用此控件之一:http://www.codeproject.com/KB/WPF/htmltextblock.aspx

Sta*_*zev 93

显示相当简单,导航是另一个问题.XAML是这样的:

<TextBlock Name="TextBlockWithHyperlink">
    Some text 
    <Hyperlink 
        NavigateUri="http://somesite.com"
        RequestNavigate="Hyperlink_RequestNavigate">
        some site
    </Hyperlink>
    some more text
</TextBlock>
Run Code Online (Sandbox Code Playgroud)

启动默认浏览器以导航到超链接的事件处理程序将是:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) {
    System.Diagnostics.Process.Start(e.Uri.ToString());
}
Run Code Online (Sandbox Code Playgroud)

编辑:要使用从数据库获得的文本来执行此操作,您必须以某种方式解析文本.一旦知道了文本部分和超链接部分,就可以在代码中动态构建文本块内容:

TextBlockWithHyperlink.Inlines.Clear();
TextBlockWithHyperlink.Inlines.Add("Some text ");
Hyperlink hyperLink = new Hyperlink() {
    NavigateUri = new Uri("http://somesite.com")
};
hyperLink.Inlines.Add("some site");
hyperLink.RequestNavigate += Hyperlink_RequestNavigate;
TextBlockWithHyperlink.Inlines.Add(hyperLink);
TextBlockWithHyperlink.Inlines.Add(" Some more text");
Run Code Online (Sandbox Code Playgroud)

  • 请注意那些找到此答案但收到“FileNotFound”异常的人:我必须将进程启动行替换为 System.Diagnostics.Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri) { UseShellExecute = true }); (2认同)

mg0*_*007 15

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

根据您的要求使用它(从这里的原始想法):

    private Regex regex = 
        new Regex(@"\[a\s+href='(?<link>[^']+)'\](?<text>.*?)\[/a\]",
        RegexOptions.Compiled);
Run Code Online (Sandbox Code Playgroud)

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

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

    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
    }
Run Code Online (Sandbox Code Playgroud)

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