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

时间:2021-07-19 06:43:56

I wrote a small WPF app where I like to prepend text into a RichTextBox, so that the newest stuff is on top. I wrote this, and it works:

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

Now I would like to make a new version of that function which can add small images as well. I'm at a loss though - is it possible to add images?

现在我想制作一个新版本的函数,可以添加小的图像。我有点不知所措——有可能添加图片吗?

2 个解决方案

#1


8  

Try the following:

试试以下:

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

The InlineUIContainer is the "magic" here... You can add any UIElement to it. If you want to add multiple items, use a panel to wrap the items (ie. StackPanel, etc)

InlineUIContainer是这里的“魔法”……你可以给它添加任何UIElement。如果您想添加多个项目,请使用面板来包装这些项目。StackPanel等)

#2


1  

RickTextbox.Document is a FlowDocument to which you can add almost anything that implements ContentElement. That includes Image, Label, StackPanel and all your other WPF favourites.

RickTextbox。Document是一个FlowDocument,您可以向其中添加几乎所有实现ContentElement的内容。这包括图像,标签,堆叠面板和所有您的其他WPF最喜欢。

Check out the FlowDocument Overview for more details.

查看FlowDocument Overview了解更多细节。

#1


8  

Try the following:

试试以下:

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

The InlineUIContainer is the "magic" here... You can add any UIElement to it. If you want to add multiple items, use a panel to wrap the items (ie. StackPanel, etc)

InlineUIContainer是这里的“魔法”……你可以给它添加任何UIElement。如果您想添加多个项目,请使用面板来包装这些项目。StackPanel等)

#2


1  

RickTextbox.Document is a FlowDocument to which you can add almost anything that implements ContentElement. That includes Image, Label, StackPanel and all your other WPF favourites.

RickTextbox。Document是一个FlowDocument,您可以向其中添加几乎所有实现ContentElement的内容。这包括图像,标签,堆叠面板和所有您的其他WPF最喜欢。

Check out the FlowDocument Overview for more details.

查看FlowDocument Overview了解更多细节。