代码之家  ›  专栏  ›  技术社区  ›  Mark Allen

如何在运行richtextblock时添加图像?

  •  1
  • Mark Allen  · 技术社区  · 16 年前

    我写了一个小的WPF应用程序,我喜欢把文本预先放进一个richtextbox,这样最新的东西就在上面了。我写了这个,它起作用了:

        /// <summary>
        /// Prepends the text to the rich textbox
        /// </summary>
        /// <param name="textoutput">The text representing the character information.</param>
        private void PrependSimpleText(string textoutput)
        {
            Run run = new Run(textoutput);
            Paragraph paragraph = new Paragraph(run);
    
            if (this.RichTextBoxOutput.Document.Blocks.Count == 0)
            {
                this.RichTextBoxOutput.Document.Blocks.Add(paragraph);
            }
            else
            {
                this.RichTextBoxOutput.Document.Blocks.InsertBefore(this.RichTextBoxOutput.Document.Blocks.FirstBlock, paragraph);
            }
        }
    

    现在我想制作一个新版本的函数,它也可以添加小图像。不过,我有点茫然——可以添加图像吗?

    2 回复  |  直到 16 年前
        1
  •  8
  •   rudigrobler    16 年前

    尝试以下操作:

    BitmapImage bi = new BitmapImage(new Uri(@"C:\SimpleImage.jpg"));
    Image image = new Image();
    image.Source = bi;
    InlineUIContainer container = new InlineUIContainer(image);            
    Paragraph paragraph = new Paragraph(container); 
    RichTextBoxOutput.Document.Blocks.Add(paragraph);
    

    inlineuicontainer是这里的“魔法”…您可以向其中添加任何uielement。如果要添加多个项目,请使用面板包装这些项目(即StackPanel等)

        2
  •  1
  •   Jan Bannister    16 年前

    document是一个流程文档,可以向其中添加几乎所有实现ContentElement的内容。包括图像、标签、StackPanel和所有其他WPF收藏。

    退房 FlowDocument Overview 了解更多详细信息。