通过绑定在TextBlock中创建超链接

问题描述 投票:4回答:3

我的问题是从文本内容中找到URL,然后通过数据绑定将其转换为可单击的超链接。

这是我尝试过的

 <TextBlock Tag="{Binding message}" x:Name="postDescription" TextWrapping="Wrap" 
  Grid.Row="3" Grid.ColumnSpan="3" Margin="10,10,10,12" FontSize="16" 
  TextAlignment="Justify" Foreground="{StaticResource foreGroundWhite}" >
    <Run Text="{Binding description, Converter={StaticResource statusFormatter}}" />
  </TextBlock>

使用代码,

public class StatusFormatter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            return returnTextWithUrl((String)value);
        }

        public static String returnTextWithUrl(String text)
        {
            if(text == null) { return null;  }
            MatchCollection mactches = uriFindRegex.Matches(text);

            foreach (Match match in mactches)
            {
                //Need Help here
                HyperlinkButton hyperlink = new HyperlinkButton();
                hyperlink.Content = match.Value;
                hyperlink.NavigateUri = new Uri(match.Value);
                text = text.Replace(match.Value, ??);
            }
            return text;
        }
}
}

输出应该是这样的

<TextBlock Tag="{Binding message}" x:Name="postDescription" TextWrapping="Wrap" 
      Grid.Row="3" Grid.ColumnSpan="3" Margin="10,10,10,12" FontSize="16" 
      TextAlignment="Justify" Foreground="{StaticResource foreGroundWhite}" >
        Click this link -
        <Hyperlink NavigateUri="http://www.bing.com">bing</Hyperlink>
        - for more info.
      </TextBlock>

有帮助吗?

c# xaml data-binding windows-phone-8.1 win-universal-app
3个回答
10
投票

要执行所需的操作,必须使用TextBlockInlines属性,但是由于它不是DependencyProperty,因此不能成为绑定的目标。我们将不得不扩展您的TextBlock类,但是由于它是sealed,因此我们将不得不使用其他类。

让我们定义static类,这将根据Regex匹配项添加适当的Inline-HyperlinkRun。它可以看起来像这样:

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)
            {
                textBl.Inlines.Clear();
                Regex regx = new Regex(@"(http://[^\s]+)", RegexOptions.IgnoreCase);
                var str = regx.Split(text);
                for (int i = 0; i < str.Length; i++)
                    if (i % 2 == 0)
                        textBl.Inlines.Add(new Run { Text = str[i] });
                    else
                    {
                        Hyperlink link = new Hyperlink { NavigateUri = new Uri(str[i]), Foreground = Application.Current.Resources["PhoneAccentBrush"] as SolidColorBrush };
                        link.Inlines.Add(new Run { Text = str[i] });
                        textBl.Inlines.Add(link);
                    }                        
            }
        }));
}

然后在XAML中,我们就这样使用它:

<TextBlock local:TextBlockExtension.FormattedText="{Binding MyText}" FontSize="15"/>

然后在我的属性中添加了一些文字:

private void firstBtn_Click(object sender, RoutedEventArgs e)
{
    MyText = @"Simple text with http://mywebsite.com link";
}

我可以看到这样的结果:

“


0
投票

我在UWP寻找相同内容时偶然发现了该信息。如果您也是一样,我建议您使用HyperlinkButton而不是包装在Hyperlink中的Textblock。下面是有关如何使用它的代码。

<HyperlinkButton Content="{x:Bind Text}" NavigateUri="{x:Bind Hyperlink}"/>

您也可以使用Binding代替x:Bind,是的,您也可以设置Mode=OneWay


-1
投票

您不能将超链接对象放在字符串中。相反,您需要从转换器返回包含内联的跨度。纯文本将是Run对象,链接将是Hyperlink对象。

    public static Span returnTextWithUrl(String text)
    {
        if(text == null) { return null;  }
        var span = new Span();
        MatchCollection mactches = uriFindRegex.Matches(text);
        int lastIndex = 0;
        foreach (Match match in mactches)
        {
            var run = new Run(text.Substring(lastIndex, match.Index - lastIndex));
            span.Inlines.Add(run);
            lastIndex = match.Index + match.Length;
            var hyperlink = new Hyperlink();
            hyperlink.Content = match.Value;
            hyperlink.NavigateUri = new Uri(match.Value);
            span.Inlines.Add(hyperlink);
        }
        span.Inlines.Add(new Run(text.Substring(lastIndex)));
        return span;
    }
© www.soinside.com 2019 - 2024. All rights reserved.