如何将图像添加到我的Run for a RichTextBlock中

本文关键字:for Run RichTextBlock 我的 图像 添加 | 更新日期: 2023-09-27 17:48:49

我写了一个小的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);
        }
    }

现在我想做一个新版本的功能,可以添加小图像,以及。不过我不知所措——可以添加图片吗?

如何将图像添加到我的Run for a RichTextBlock中

尝试以下操作:

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等)

RickTextbox.Document是一个FlowDocument,您几乎可以向其中添加任何实现ContentElement的内容。其中包括图像、标签、StackPanel和所有其他WPF收藏夹。

查看FlowDocument概述以了解更多详细信息。