Beispiel #1
0
        /// <summary>
        /// Sets the linked HTML fragment.
        /// </summary>
        /// <remarks>
        /// Note that only simple html text with opening and closing anchor tags and href attribute with double-quotes is supported.
        /// No escapes or other tags will be parsed.
        /// </remarks>
        /// <param name="richTextBlock">The rich text block.</param>
        /// <param name="htmlFragment">The HTML fragment.</param>
        public static void SetLinkedHtmlFragmentString(this RichTextBlock richTextBlock, string htmlFragment)
        {
            richTextBlock.Blocks.Clear();

            if (string.IsNullOrEmpty(htmlFragment))
            {
                return;
            }

            var regEx = new Regex(
                @"\<a\s(href\=""|[^\>]+?\shref\="")(?<link>[^""]+)"".*?\>(?<text>.*?)(\<\/a\>|$)",
                RegexOptions.IgnoreCase | RegexOptions.Multiline);

            int nextOffset = 0;

            foreach (Match match in regEx.Matches(htmlFragment))
            {
                if (match.Index > nextOffset)
                {
                    richTextBlock.AppendText(htmlFragment.Substring(nextOffset, match.Index - nextOffset));
                    nextOffset = match.Index + match.Length;
                    richTextBlock.AppendLink(match.Groups["text"].Value, new Uri(match.Groups["link"].Value));
                }

                //Debug.WriteLine(match.Groups["text"] + ":" + match.Groups["link"]);
            }

            if (nextOffset < htmlFragment.Length)
            {
                richTextBlock.AppendText(htmlFragment.Substring(nextOffset));
            }
        }