Example #1
0
 private static Run BuildRunForRTBStyle(string text, RichTextBlock rtb)
 {
     return(new Run {
         Text = text,
         FontFamily = rtb.FontFamily,
     });
 }
Example #2
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));
            }
        }
Example #3
0
        public void ReactTextViewManager_Selection_HyperlinkText()
        {
            // <Span><Run>Sample test text.</Run><Run>Second text.</Run></Span><Run>Third text.</Run><Span><Hyperlink NavigateUri='http://www.test.com'>HyperlinkTest.</Hyperlink></Span>
            Span span = new Span();
            Run  run  = new Run();

            run.Text = "Sample test text.";
            span.Inlines.Add(run);
            Run run1 = new Run();

            run1.Text = "Second text.";
            span.Inlines.Add(run1);
            Run run2 = new Run();

            run2.Text = "Third text.";
            Span      span1     = new Span();
            Hyperlink hyperlink = new Hyperlink();

            hyperlink.NavigateUri = new System.Uri("http://www.test.com");
            span1.Inlines.Add(hyperlink);

            RichTextBlock rtb       = CreateWithInlines(new Inline[] { span, run2, span1 });
            Paragraph     paragraph = rtb.Blocks.First() as Paragraph;
            TextPointer   start     = paragraph.ContentStart.GetPositionAtOffset(49, LogicalDirection.Forward);
            TextPointer   end       = paragraph.ContentStart.GetPositionAtOffset(50, LogicalDirection.Forward);
            var           text      = ReactTextViewManager.GetStringByStartAndEndPointers(rtb, start, end);

            Assert.AreEqual(text, @"http://www.test.com/");
        }
        /// <summary>
        /// This is called when the HTML has changed so that we can generate RT content
        /// </summary>
        /// <param name="d"></param>
        /// <param name="e"></param>
        private static void HtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            RichTextBlock richText = d as RichTextBlock;

            if (richText == null)
            {
                return;
            }

            //Generate blocks
            string xhtml = e.NewValue as string;

            string baselink = "";
            //if (richText.DataContext is iFixit.Domain.Models.UI.GuideStepLine)
            //{
            //    iFixit.Domain.Models.UI.GuideStepLine bp = richText.DataContext as iFixit.Domain.Models.UI.GuideStepLine;
            //    baselink = "http://" + bp.Link.Host;
            //}

            List <Block> blocks = GenerateBlocksForHtml(xhtml, baselink);

            //Add the blocks to the RichTextBlock
            try
            {
                richText.Blocks.Clear();
                foreach (Block b in blocks)
                {
                    richText.Blocks.Add(b);
                }
            }
            catch (Exception)
            {
                Debug.WriteLine("problems with richtextblock!");
            }
        }
Example #5
0
        public void ReactTextViewManager_Selection_SpanText()
        {
            // <Span><Run>Sample test text.</Run><Run>Second text.</Run></Span><Run>Third text.</Run><Span><Run>Fourth text.</Run></Span>
            Span span = new Span();
            Run  run  = new Run();

            run.Text = "Sample test text.";
            span.Inlines.Add(run);
            Run run1 = new Run();

            run1.Text = "Second text.";
            span.Inlines.Add(run1);
            Run run2 = new Run();

            run2.Text = "Third text.";
            Span span1 = new Span();
            Run  run3  = new Run();

            run3.Text = "Fourth text.";
            span1.Inlines.Add(run3);

            RichTextBlock rtb       = CreateWithInlines(new Inline[] { span, run2, span1 });
            Paragraph     paragraph = rtb.Blocks.First() as Paragraph;
            TextPointer   start     = paragraph.ContentStart.GetPositionAtOffset(50, LogicalDirection.Forward);
            TextPointer   end       = paragraph.ContentStart.GetPositionAtOffset(54, LogicalDirection.Forward);
            var           text      = ReactTextViewManager.GetStringByStartAndEndPointers(rtb, start, end);

            Assert.AreEqual(text, @"Four");
        }
Example #6
0
        public void ReactTextViewManager_Selection_BoldUnderlineText()
        {
            // <Bold><Run>Sample test text.</Run><Run>Second text.</Run></Bold><Run>Third text.</Run><Underline><Run>Fourth text.</Run></Underline>
            Bold bold = new Bold();
            Run  run  = new Run();

            run.Text = "Sample test text.";
            bold.Inlines.Add(run);
            Run run1 = new Run();

            run1.Text = "Second text.";
            bold.Inlines.Add(run1);
            Run run2 = new Run();

            run2.Text = "Third text.";
            Underline underline = new Underline();
            Run       run3      = new Run();

            run3.Text = "Fourth text.";
            underline.Inlines.Add(run3);

            RichTextBlock rtb       = CreateWithInlines(new Inline[] { bold, run2, underline });
            Paragraph     paragraph = rtb.Blocks.First() as Paragraph;
            TextPointer   start     = paragraph.ContentStart.GetPositionAtOffset(50, LogicalDirection.Forward);
            TextPointer   end       = paragraph.ContentStart.GetPositionAtOffset(54, LogicalDirection.Forward);
            var           text      = ReactTextViewManager.GetStringByStartAndEndPointers(rtb, start, end);

            Assert.AreEqual(text, @"Four");
        }
Example #7
0
        public void ReactTextViewManager_Selection_EmbeddedSpan()
        {
            // <Span><Run>@</Run><Span><Run>First text.</Run></Span><Run>Third text.</Run></Span>
            Span span = new Span();
            Run  run  = new Run();

            run.Text = "@";
            span.Inlines.Add(run);
            Span span1 = new Span();
            Run  run1  = new Run();

            run1.Text = "First text.";
            span1.Inlines.Add(run1);
            span.Inlines.Add(span1);
            Run run2 = new Run();

            run2.Text = "Third text.";
            span.Inlines.Add(run2);

            RichTextBlock rtb       = CreateWithInlines(new Inline[] { span });
            Paragraph     paragraph = rtb.Blocks.First() as Paragraph;
            TextPointer   start     = paragraph.ContentStart.GetPositionAtOffset(7, LogicalDirection.Forward);
            TextPointer   end       = paragraph.ContentStart.GetPositionAtOffset(8, LogicalDirection.Forward);
            var           text      = ReactTextViewManager.GetStringByStartAndEndPointers(rtb, start, end);

            Assert.AreEqual(text, @"i");
        }
Example #8
0
        public void ReactTextViewManager_Selection_InlineUIContainer()
        {
            // <Span><Run>Sample test text.</Run><Run>Second text.</Run></Span><Run>Third text.</Run><InlineUIContainer><TextBlock Text='InlineUIContainerText'/></InlineUIContainer>
            Span span = new Span();
            Run  run  = new Run();

            run.Text = "Sample test text.";
            span.Inlines.Add(run);
            Run run1 = new Run();

            run1.Text = "Second text.";
            span.Inlines.Add(run1);
            Run run2 = new Run();

            run2.Text = "Third text.";
            InlineUIContainer inlineUIContainer = new InlineUIContainer();
            TextBlock         tb = new TextBlock();

            tb.Text = "InlineUIContainerText";
            inlineUIContainer.Child = tb;

            RichTextBlock rtb       = CreateWithInlines(new Inline[] { span, run2, inlineUIContainer });
            Paragraph     paragraph = rtb.Blocks.First() as Paragraph;
            TextPointer   start     = paragraph.ContentStart.GetPositionAtOffset(49, LogicalDirection.Forward);
            TextPointer   end       = paragraph.ContentStart.GetPositionAtOffset(50, LogicalDirection.Forward);
            var           text      = ReactTextViewManager.GetStringByStartAndEndPointers(rtb, start, end);

            Assert.AreEqual(text, @"InlineUIContainerText");
        }
Example #9
0
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            //Create a new RichTextBox.
            RichTextBlock MyRTB = new RichTextBlock();

            // Create a Run of plain text and hyperlink.
            Run myRun = new Run();

            myRun.Text = " are enabled in a read-only RichTextBox.";
            InlineUIContainer mylinkcont = new InlineUIContainer();
            HyperlinkButton   MyLink     = new HyperlinkButton();

            MyLink.Content     = "Hyperlink";
            MyLink.NavigateUri = new Uri("http://www.msdn.com");

            mylinkcont.Child = MyLink;
            // Create a paragraph and add the Run and hyperlink to it.
            Paragraph myParagraph = new Paragraph();

            myParagraph.Inlines.Add(mylinkcont);
            myParagraph.Inlines.Add(myRun);

            // Add the paragraph to the RichTextBox.
            MyRTB.Blocks.Add(myParagraph);

            return(MyRTB);
        }
        // This is the ReSharper 8.1 version
        public RichTextBlock GetElementDescription(IDeclaredElement element, DeclaredElementDescriptionStyle style,
                                                   PsiLanguageType language, IPsiModule module)
        {
            var attribute = element as IHtmlAttributeDeclaredElement;
            if (attribute == null)
                return null;

            var attributeDescription = GetAttributeDescription(attribute.ShortName);

            var block = new RichTextBlock();
            var typeDescription = new RichText(htmlDescriptionsCache.GetDescriptionForHtmlValueType(attribute.ValueType));
            if (style.IntendedDescriptionPlacement == DescriptionPlacement.AFTER_NAME &&
                (style.ShowSummary || style.ShowFullDescription))
                block.SplitAndAdd(typeDescription);

            string description = null;
            if (style.ShowSummary && attributeDescription != null)
                description = attributeDescription.Summary;
            else if (style.ShowFullDescription && attributeDescription != null)
                description = attributeDescription.Description;

            if (!string.IsNullOrEmpty(description))
                block.SplitAndAdd(description);

            if (style.IntendedDescriptionPlacement == DescriptionPlacement.ON_THE_NEW_LINE &&
                (style.ShowSummary || style.ShowFullDescription))
            {
                // TODO: Perhaps we should show Value: Expression for attributes that take an Angular expression, etc
                typeDescription.Prepend("Value: ");
                block.SplitAndAdd(typeDescription);
            }

            return block;
        }
Example #11
0
        private void UpdateTextBlockCore(RichTextBlock textBlock, bool measureOnly)
        {
            textBlock.CharacterSpacing         = _letterSpacing;
            textBlock.LineHeight               = _lineHeight;
            textBlock.MaxLines                 = _numberOfLines;
            textBlock.TextAlignment            = _textAlignment;
            textBlock.FontFamily               = _fontFamily != null ? new FontFamily(_fontFamily) : FontFamily.XamlAutoFontFamily;
            textBlock.FontSize                 = _fontSize ?? 15;
            textBlock.FontStyle                = _fontStyle ?? FontStyle.Normal;
            textBlock.FontWeight               = _fontWeight ?? FontWeights.Normal;
            textBlock.IsTextScaleFactorEnabled = _allowFontScaling;

            if (!measureOnly)
            {
                var x = GetPadding(YogaEdge.Left);
                if (x != 0)
                {
                    ;
                }

                textBlock.Padding = new Thickness(
                    GetPadding(YogaEdge.Left),
                    GetPadding(YogaEdge.Top),
                    GetPadding(YogaEdge.Right),
                    GetPadding(YogaEdge.Bottom));
            }
        }
        /// <summary>
        /// Creates a new RichTextBlock, if the last element of the provided collection isn't already a RichTextBlock.
        /// </summary>
        /// <returns>The rich text block</returns>
        protected RichTextBlock CreateOrReuseRichTextBlock(IRenderContext context)
        {
            var localContext = context as UIElementCollectionRenderContext;

            if (localContext == null)
            {
                throw new RenderContextIncorrectException();
            }

            var blockUIElementCollection = localContext.BlockUIElementCollection;

            // Reuse the last RichTextBlock, if possible.
            if (blockUIElementCollection != null && blockUIElementCollection.Count > 0 && blockUIElementCollection[blockUIElementCollection.Count - 1] is RichTextBlock)
            {
                return((RichTextBlock)blockUIElementCollection[blockUIElementCollection.Count - 1]);
            }

            var result = new RichTextBlock
            {
                CharacterSpacing       = CharacterSpacing,
                FontFamily             = FontFamily,
                FontSize               = FontSize,
                FontStretch            = FontStretch,
                FontStyle              = FontStyle,
                FontWeight             = FontWeight,
                Foreground             = localContext.Foreground,
                IsTextSelectionEnabled = IsTextSelectionEnabled,
                TextWrapping           = TextWrapping
            };

            localContext.BlockUIElementCollection?.Add(result);

            return(result);
        }
        private void FormatAndRenderSampleFromString(String sampleString, ContentPresenter presenter, ILanguage highlightLanguage)
        {
            // Trim out stray blank lines at start and end.
            sampleString = sampleString.TrimStart('\n').TrimEnd();

            // Perform any applicable substitutions.
            sampleString = SubstitutionPattern.Replace(sampleString, match =>
            {
                foreach (var substitution in Substitutions)
                {
                    if (substitution.Key == match.Groups[1].Value)
                    {
                        return(substitution.ValueAsString());
                    }
                }
                throw new KeyNotFoundException(match.Groups[1].Value);
            });

            var sampleCodeRTB = new RichTextBlock();

            sampleCodeRTB.FontFamily = new FontFamily("Consolas");

            var formatter = GenerateRichTextFormatter();

            formatter.FormatRichTextBlock(sampleString, highlightLanguage, sampleCodeRTB);
            presenter.Content = sampleCodeRTB;
        }
Example #14
0
        private FrameworkElement ProcessList(PageBlockList block)
        {
            var textBlock = new RichTextBlock();

            textBlock.FontSize     = 17;
            textBlock.TextWrapping = TextWrapping.Wrap;

            for (int i = 0; i < block.Items.Count; i++)
            {
                var text = block.Items[i];
                var par  = new Paragraph();
                par.TextIndent = -24;
                par.Margin     = new Thickness(24, 0, 0, 0);

                var span = new Span();
                par.Inlines.Add(new Run {
                    Text = block.IsOrdered ? (i + 1) + ".\t" : "•\t"
                });
                par.Inlines.Add(span);
                ProcessRichText(text, span);
                textBlock.Blocks.Add(par);
            }

            return(textBlock);
        }
Example #15
0
        public async void Render(News news)
        {
            if (NetworkService.IsNetworkAvailable() == false)
            {
                await new DialogService().ShowMessageBox("请检查网络连接。", "错误");
                return;
            }
            this.IsLoading = true;
            Exception exception = null;

            try
            {
                var newsDetail = await NewsService.DetailAsync(news.Id);

                this.Title = newsDetail.Title;
                var richTextBlock = new RichTextBlock()
                {
                    FontSize = 16,
                    Margin   = new Thickness(20, 0, 20, 10),
                    IsTextSelectionEnabled = false
                };
                var context = new RenderContextBase(newsDetail.Content);
                context.Render(richTextBlock);
                this.NewsDetail = richTextBlock;
            }
            catch (Exception ex)
            {
                exception = ex;
            }
            if (exception != null)
            {
                await new DialogService().ShowError(exception, "错误", "关闭", null);
            }
            this.IsLoading = false;
        }
Example #16
0
        /// <summary>
        /// Creates a new RichTextBlock, if the last element of the provided collection isn't already a RichTextBlock.
        /// </summary>
        /// <returns>The rich text block</returns>
        private RichTextBlock CreateOrReuseRichTextBlock(UIElementCollection blockUIElementCollection, RenderContext context)
        {
            // Reuse the last RichTextBlock, if possible.
            if (blockUIElementCollection != null && blockUIElementCollection.Count > 0 && blockUIElementCollection[blockUIElementCollection.Count - 1] is RichTextBlock)
            {
                return((RichTextBlock)blockUIElementCollection[blockUIElementCollection.Count - 1]);
            }

            var result = new RichTextBlock
            {
                CharacterSpacing       = CharacterSpacing,
                FontFamily             = FontFamily,
                FontSize               = FontSize,
                FontStretch            = FontStretch,
                FontStyle              = FontStyle,
                FontWeight             = FontWeight,
                Foreground             = context.Foreground,
                IsTextSelectionEnabled = IsTextSelectionEnabled,
                TextWrapping           = TextWrapping
            };

            blockUIElementCollection?.Add(result);

            return(result);
        }
Example #17
0
        private IdentifierTooltipContent TryPresentNonColorized(
            [CanBeNull] IHighlighter highlighter,
            [CanBeNull] IDeclaredElement element,
            [NotNull] IContextBoundSettingsStore settings)
        {
            RichTextBlock richTextToolTip = highlighter?.RichTextToolTip;

            if (richTextToolTip == null)
            {
                return(null);
            }

            RichText richText = richTextToolTip.RichText;

            if (richText.IsNullOrEmpty())
            {
                return(null);
            }

            var identifierContent = new IdentifierTooltipContent(richText, highlighter.Range);

            if (element != null && settings.GetValue((IdentifierTooltipSettings s) => s.ShowIcon))
            {
                identifierContent.Icon = TryGetIcon(element);
            }
            return(identifierContent);
        }
Example #18
0
        private static async void HtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            RichTextBlock richText = d as RichTextBlock;
            string        html     = e.NewValue as string;

            if (richText != null && !string.IsNullOrEmpty(html))
            {
                try
                {
                    if (GetContainsCrlf(d))
                    {
                        html = html.Replace("\r\n", "<br/>");
                        html = html.Replace("\n\r", "<br/>");
                        html = html.Replace("\n", "<br/>");
                    }

                    string xaml = await Html2Xaml.ConvertToXaml(html);

                    ChangeRichTextBlockContents(richText, xaml);
                }
                catch (Exception ex)
                {
                    AppLogs.WriteError("Html2Xaml.HtmlChanged", ex);
                    try
                    {
                        ChangeRichTextBlockContents(richText, GetErrorXaml(ex, html));
                    }
                    catch
                    {
                        AppLogs.WriteError("Html2Xaml.HtmlChanged", ex);
                    }
                }
            }
        }
        /// <summary>
        /// Adds Syntax Highlighted Source Code to the provided RichTextBlock.
        /// </summary>
        /// <param name="sourceCode">The source code to colorize.</param>
        /// <param name="language">The language to use to colorize the source code.</param>
        /// <param name="RichText">The Control to add the Text to.</param>
        public void FormatRichTextBlock(string sourceCode, ILanguage Language, RichTextBlock RichText)
        {
            var paragraph = new Paragraph();

            RichText.Blocks.Add(paragraph);
            FormatInlines(sourceCode, Language, paragraph.Inlines);
        }
 private void AddLines(RichTextBlock layout)
 {
     foreach (var line in _lines)
     {
         layout.Blocks.Add(line.Value);
     }
 }
        private void AddPages(Size containerSize, RichTextBlock layout)
        {
            if (_flip.Items != null)
            {
                _flip.Items.Add(new FlipViewItem {
                    Content = layout
                });
                layout.Measure(containerSize);

                if (layout.HasOverflowContent)
                {
                    var richTextBlockOverflow = new RichTextBlockOverflow();
                    layout.OverflowContentTarget = richTextBlockOverflow;
                    _flip.Items.Add(new FlipViewItem()
                    {
                        Content = richTextBlockOverflow
                    });
                    richTextBlockOverflow.Measure(containerSize);

                    while (richTextBlockOverflow.HasOverflowContent)
                    {
                        var newRichTextBlockOverflow = new RichTextBlockOverflow();
                        richTextBlockOverflow.OverflowContentTarget = newRichTextBlockOverflow;
                        richTextBlockOverflow = newRichTextBlockOverflow;
                        _flip.Items.Add(new FlipViewItem()
                        {
                            Content = richTextBlockOverflow
                        });
                        richTextBlockOverflow.Measure(containerSize);
                    }
                }
            }
        }
        private StackPanel GenerateOL(IHtmlOrderedListElement node)
        {
            var verticalStackPanel = new StackPanel();

            int number = node.Start;

            foreach (var child in node.ChildNodes)
            {
                if (String.IsNullOrWhiteSpace(child.TextContent))
                {
                    continue;
                }

                var horizontalStackPanel = new StackPanel()
                {
                    Orientation = Orientation.Horizontal, Margin = new Thickness(0, 3, 0, 3)
                };
                horizontalStackPanel.Children.Add(new TextBlock()
                {
                    Text = $"{number}.", Margin = new Thickness(9.5, 0, 9.5, 0)
                });
                number++;

                var richTextBlock = new RichTextBlock();
                var paragraph     = new Paragraph();

                AddInlineChildren(child, paragraph.Inlines);

                richTextBlock.Blocks.Add(paragraph);
                horizontalStackPanel.Children.Add(richTextBlock);
                verticalStackPanel.Children.Add(horizontalStackPanel);
            }

            return(verticalStackPanel);
        }
Example #23
0
        private void Overflow(RichTextBlock rtb)
        {
            void Flow()
            {
                if (rtb.HasOverflowContent && rtb.OverflowContentTarget == null)
                {
                    var index  = IndexOf(rtb);
                    var target = new RichTextBlockOverflow
                    {
                        MaxWidth = 800
                    };
                    target.SetBinding(RichTextBlockOverflow.PaddingProperty, _bindings.PaddingBinding);
                    rtb.OverflowContentTarget = target;
                    Insert(index + 1, target);
                    target.UpdateLayout();
                    Overflow(target);
                }

                else if (!rtb.HasOverflowContent && rtb.OverflowContentTarget != null)
                {
                    Remove(rtb.OverflowContentTarget);
                    rtb.OverflowContentTarget = null;
                }
            }

            rtb.SizeChanged += (s, e) =>
            {
                Flow();
            };

            Flow();
            // rtb.RegisterPropertyChangedCallback(RichTextBlock.HasOverflowContentProperty, HasOverflowContentPropertyChanged);
        }
Example #24
0
        public static Hyperlink GetHyperlinkFromPoint(this RichTextBlock text, Point point)
        {
            var position  = text.GetPositionFromPoint(point);
            var hyperlink = GetHyperlink(position.Parent as TextElement);

            return(hyperlink);
        }
Example #25
0
        private static YogaSize MeasureText(ReactTextShadowNode textNode, YogaNode node, float width, YogaMeasureMode widthMode, float height, YogaMeasureMode heightMode)
        {
            // TODO: Measure text with DirectWrite or other API that does not
            // require dispatcher access. Currently, we're instantiating a
            // second CoreApplicationView (that is never activated) and using
            // its Dispatcher thread to calculate layout.
            var textBlock = new RichTextBlock
            {
                TextWrapping  = TextWrapping.Wrap,
                TextAlignment = TextAlignment.DetectFromContent,
                TextTrimming  = TextTrimming.CharacterEllipsis,
            };

            textNode.UpdateTextBlockCore(textBlock, true);

            var block = new Paragraph();

            for (var i = 0; i < textNode.ChildCount; ++i)
            {
                var child = textNode.GetChildAt(i);
                block.Inlines.Add(ReactInlineShadowNodeVisitor.Apply(child));
            }
            textBlock.Blocks.Add(block);

            var normalizedWidth  = YogaConstants.IsUndefined(width) ? double.PositiveInfinity : width;
            var normalizedHeight = YogaConstants.IsUndefined(height) ? double.PositiveInfinity : height;

            textBlock.Measure(new Size(normalizedWidth, normalizedHeight));
            return(MeasureOutput.Make(
                       (float)Math.Ceiling(textBlock.DesiredSize.Width),
                       (float)Math.Ceiling(textBlock.DesiredSize.Height)));
        }
    /// <summary>
    /// This is called when the HTML has changed so that we can generate RT content
    /// </summary>
    /// <param name="d"></param>
    /// <param name="e"></param>
    private static void HtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        RichTextBlock richText = d as RichTextBlock;

        if (richText == null)
        {
            return;
        }

        //Generate blocks
        string xhtml = e.NewValue as string;

        string baselink = "";

        List <Block> blocks = GenerateBlocksForHtml(xhtml, baselink);

        //Add the blocks to the RichTextBlock
        try
        {
            richText.Blocks.Clear();
            foreach (Block b in blocks)
            {
                richText.Blocks.Add(b);
            }
        }
        catch (Exception)
        {
            Debug.WriteLine("problems with richtextblock!");
        }
    }
Example #27
0
        private static void HtmlChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is RichTextBlock)
            {
                string html = e.NewValue as string;

                RichTextBlock richText = d as RichTextBlock;
                if (richText == null)
                {
                    return;
                }

                richText.Blocks.Clear();

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("<?xml version=\"1.0\"?>");
                sb.AppendLine("<RichTextBlock xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">");
                sb.AppendLine(Html2XamlConverter.Convert2Xaml(html, TagAttributes));
                sb.AppendLine("</RichTextBlock>");

                RichTextBlock newRichText = (RichTextBlock)XamlReader.Load(sb.ToString());

                for (int i = newRichText.Blocks.Count - 1; i >= 0; i--)
                {
                    Block b = newRichText.Blocks[i];
                    newRichText.Blocks.RemoveAt(i);
                    richText.Blocks.Insert(0, b);
                }
            }
        }
Example #28
0
        public static void FromHtml(RichTextBlock rtb, string html)
        {
            var oldHtml = html;

            html = System.Net.WebUtility.HtmlDecode(html);
            html = html.Replace("&bull;", "<br />    - ");
            html = html.Replace("&middot;", "<br />    - ");
            html = html.Replace("<li>", "    - ").Replace("</li>", "<br />").Replace("<ul>", "<p>").Replace("</ul>", "</p>");

            html = html.Replace("<br /><br /><p>", "<br /><p>");

            html = $"<html><body><p>{html}</p></body></html>";
            var v           = new XmlConvert();
            var htmlFromDoc = v.Convert(html);

            htmlFromDoc = htmlFromDoc.Replace("<p />", "");
            XmlDocument document = new XmlDocument();

            document.LoadXml(htmlFromDoc);

            XmlElement elem = (XmlElement)(document.GetElementsByTagName("body")[0]);

            var container = new RichTextBlockTextContainer(rtb);

            ParseElement(elem, container);
        }
Example #29
0
        void RefreshTagsWrapBlock(RichTextBlock tagsWrapBlock)
        {
            tagsWrapBlock.Blocks.Clear();
            if (this.GalleryViewModel?.Gallery?.Tags == null)
            {
                return;
            }

            var groupedTags = this.GalleryViewModel.Gallery.Tags.GroupBy(o => o.Slave);

            foreach (var group in groupedTags)
            {
                var p = new Paragraph();

                var gOrdered = group.OrderBy(o => o.Name.Length);
                foreach (var item in gOrdered)
                {
                    var button = new ContentControl()
                    {
                        ContentTemplate = this.Resources["TagButtonTemplate"] as DataTemplate, DataContext = item
                    };
                    var i = new InlineUIContainer()
                    {
                        Child = button
                    };
                    p.Inlines.Add(i);
                }
                tagsWrapBlock.Blocks.Add(p);
            }
        }
Example #30
0
        protected override void OnApplyTemplate()
        {
            if (_printButton != null)
            {
                _printButton.Click -= PrintButton_Click;
            }

            if (_copyButton != null)
            {
                _copyButton.Click -= CopyButton_Click;
            }

            _codeView    = GetTemplateChild("codeView") as RichTextBlock;
            _printButton = GetTemplateChild("PrintButton") as Button;
            _copyButton  = GetTemplateChild("CopyButton") as Button;
            _container   = GetTemplateChild("Container") as Grid;

            if (_printButton != null)
            {
                _printButton.Click += PrintButton_Click;
            }

            if (_copyButton != null)
            {
                _copyButton.Click += CopyButton_Click;
            }

            if (!_rendered)
            {
                RenderDocument();
            }

            base.OnApplyTemplate();
        }
Example #31
0
        public void CreateFromBlocks(IEnumerable <Block> blocks, PageProviderBindings bindings, bool canGoBack, bool canGoForward)
        {
            _bindings = bindings;

            if (canGoBack)
            {
                Add(new FlipViewItem());
            }

            var baseBlock = new RichTextBlock
            {
                IsTextSelectionEnabled = false
            };

            baseBlock.SetBinding(RichTextBlock.LineHeightProperty, _bindings.LineHeightBinding);
            baseBlock.SetBinding(RichTextBlock.PaddingProperty, _bindings.PaddingBinding);
            baseBlock.SetBinding(RichTextBlock.TextIndentProperty, _bindings.ParagraphIndentationBinding);
            baseBlock.MaxWidth = 800;

            foreach (var block in blocks)
            {
                baseBlock.Blocks.Add(block);
            }

            Add(baseBlock);
            baseBlock.UpdateLayout();
            Overflow(baseBlock);

            if (canGoForward)
            {
                Add(new FlipViewItem());
            }
        }
        public bool? IsElementObsolete(IDeclaredElement element, out RichTextBlock obsoleteDescription,
                                       DeclaredElementDescriptionStyle style)
        {
            obsoleteDescription = null;
            var obsoletable = element as IObsoletable;
            if (obsoletable == null)
                return null;

            if (!obsoletable.Obsolete && !obsoletable.NonStandard)
                return false;

            obsoleteDescription = new RichTextBlock();
            var richText = new RichText();
            if (obsoletable.Obsolete)
                richText.Append("Obsolete!", new TextStyle(FontStyle.Bold));
            else if (obsoletable.NonStandard)
                richText.Append("Non-standard!", new TextStyle(FontStyle.Bold));

            obsoleteDescription.Add(richText);

            return true;
        }
 public bool? IsElementObsolete(IDeclaredElement element, out RichTextBlock obsoleteDescription,
     DeclaredElementDescriptionStyle style)
 {
     obsoleteDescription = null;
     return false;
 }
		public void GetParametersInfo(out string[] paramNames, out RichTextBlock[] paramDescriptions, out bool isParamsArray) {
			_underlyingCandidate.GetParametersInfo(out paramNames, out paramDescriptions, out isParamsArray);
		}