Create Hyperlink in TextBlock via Binding

前端 未结 3 530
死守一世寂寞
死守一世寂寞 2020-12-19 09:40

My problem is to find the urls from the text content and convert it into the clickable hyperlinks via data binding.

This is what I\'ve tried

 

        
3条回答
  •  独厮守ぢ
    2020-12-19 10:08

    You can't put Hyperlink objects inside a String. Instead you need to return a Span containing inlines from your converter. The plain text will be Run objects and the links will be Hyperlink objects.

        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;
        }
    

提交回复
热议问题