.NET Framework Bookmark and Share   
 index > Windows Presentation Foundation (WPF) > inserting image into richtextbox control
 

inserting image into richtextbox control

Haw can I insert image control into richtextbox in certain place?

Thansk for any help

Rajmund

Rajmund Paczkowski
Hi,

I'm sorry. It's even easier. I always thought a WPF element had to be in a BlockUIContainer in a FlowDocument, but apparently, the code below works too and this way you can put an image between two Inlines:

private void btn_Click(object sender, RoutedEventArgs e)
{

Paragraph para = new Paragraph();
para.Inlines.Add("Some ");

BitmapImage bitmap = new BitmapImage(new Uri(@"<your picture url>"));
Image image = new Image();
image.Source = bitmap;
image.Width = 20;
para.Inlines.Add(image);

para.Inlines.Add(" text");
fld.Blocks.Add(para);
}

Best regards,

Benny
Benny Tops
Hi,

You can't put a WPF Image control directly into a RichTextBox. You have to wrap it in at least a BlockUIContainer.

A WPF RichTextBox operates on a FlowDocument like this:

<RichTextBox>
<FlowDocument>
...
</FlowDocument>
</RichTextBox>

To put an image in a FlowDocument you have to put it in a BlockUIContainer. This is the class that takes care of showing WPF elements in a FlowDocument. The Figure class is also of use. With the Figure class you can create an advanced layout, e.g. an image with text flowing around.

<RichTextBox xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlnsTongue Tiedys="clr-namespaceTongue Tiedystem;assembly=mscorlib" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<FlowDocument>
<Paragraph>Integer lacinia, purus a sollicitudin elementum, tortor dolor volutpat enim, sit amet ultrices tortor lacus dignissim magna.</Paragraph>
<Paragraph>
<Figure Width="200">
<BlockUIContainer>
<Image Source="<Your image>"/>
</BlockUIContainer>
</Figure>
</Paragraph>
</FlowDocument>
</RichTextBox>

Hope this helps.

Best regards,

Benny
Benny Tops

I forgot to say that i want to insert image from C# code, let's say on button click event.

Rajmund Paczkowski
From code it's exactly the same:

<Window x:Class="InsertImage.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="InsertImage" Height="300" Width="300"
>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<RichTextBox x:Name="rtb" VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
<FlowDocument x:Name="fld">

</FlowDocument>
</RichTextBox>
<Button x:Name="btn" Grid.Row="1" Click="btn_Click">Insert Image</Button>
</Grid>
</Window>


using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace InsertImage
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>

public partial class Window1 : System.Windows.Window
{

public Window1()
{
InitializeComponent();
}

private void btn_Click(object sender, RoutedEventArgs e)
{
// Add some text
Paragraph para = new Paragraph();
para.Inlines.Add(new Run("Image "));
fld.Blocks.Add(para);

// Add an image
para = new Paragraph();
BitmapImage bitmap = new BitmapImage(new Uri(<Uri to your image>));
Image image = new Image();
image.Source = bitmap;
Figure figure = new Figure();
figure.Width = new FigureLength(200);
BlockUIContainer container = new BlockUIContainer(image);
figure.Blocks.Add(container);
para.Inlines.Add(figure);
fld.Blocks.Add(para);

}
}
}
Benny Tops

Thanks a lot for your help.

I have one more question. Your example put image at the end of the richtextbox content.

Let's say we have "Some text" string in richtextbox. How to insert image between "Some" and "text"?

Rajmund Paczkowski
Hi,

I'm sorry. It's even easier. I always thought a WPF element had to be in a BlockUIContainer in a FlowDocument, but apparently, the code below works too and this way you can put an image between two Inlines:

private void btn_Click(object sender, RoutedEventArgs e)
{

Paragraph para = new Paragraph();
para.Inlines.Add("Some ");

BitmapImage bitmap = new BitmapImage(new Uri(@"<your picture url>"));
Image image = new Image();
image.Source = bitmap;
image.Width = 20;
para.Inlines.Add(image);

para.Inlines.Add(" text");
fld.Blocks.Add(para);
}

Best regards,

Benny
Benny Tops
Hi,
I want to be able to save and to open my picture and all the text that I have in my rich text. Actually, when I do the save(.Xaml file) Ilose my picture and I only see the text.

Any idea??

Thank you,
Titima.
Titima
You can use TextRange.Save() with DataFormats.XamlPackage to save images.
Juhani Torkkola - MSFT
Thank you Juhani for your response

In fact, I needto save my richTexttext+image to the database. Here is my code :

private void cmdSave_Click(object sender, RoutedEventArgs e) {

SaveFileDialog saveFile = new SaveFileDialog(); "Files (*.xaml)|*.xaml";
if (saveFile.ShowDialog() == true
)
//Create a TextRange around the entire document.

{

TextRange documentTextRange = new TextRange( richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd);

//If this file exists, it's overwritten.

using (FileStream fs = File.Create(saveFile.FileName))
{

documentTextRange.Save(fs, DataFormats.XamlPackage);
}
}



byte
[] bytes;
using (FileStream fs = new FileStream(saveFile.FileName, FileMode.Open))
{
bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);

data = bytes;
}


"data" is a local variableused in order to experiment the load from the database.

private void cmdOpen_Click(object sender, RoutedEventArgs e)

{

OpenFileDialog openFile = new OpenFileDialog();
using (MemoryStream ms = new MemoryStream(data)) {

FlowDocument fl = new FlowDocument();

TextRange tr = new TextRange(fl.ContentStart, fl.ContentEnd); DataFormats.XamlPackage);
richTextBox1.Document = fl;

tr.Load(ms,

ms.Close();
}
}

When loading my content using "tr.Load(ms, DataFormats.XamlPackage);" instruction, I get this error : "Unrecognized structure in data format 'XamlPackage'. Parameter name: stream"

I don't know the reason of getting this error all my code seems to me fine. Do you have any idea or solution?

Thank you.

  • Proposed As Answer byBoanerge Tuesday, September 22, 2009 12:27 PM
  •  
Titima
Check if you are opening a xaml file, the xamlpackege is NOT a xaml file but a binary file.

I already saved the xamlPackage data format todatabase inntext column but I dit it using Convert.ToBase64String.

You cannot open an xaml file using the xamlpackage format.

For my already saved data (using xaml format) I used an (not recomended) workaroundto loadthe old data.
try
{
rtb.SetContent(Convert.FromBase64String(this.Service.Information.InformationGuide));
}
catch (FormatException)
{
rtb.SetContent(ASCIIEncoding.Default.GetBytes(this.Service.Information.InformationGuide));
}


MySetContentmethod:

public void SetContent(byte[] Content)

{

TextRange tr = new TextRange(rtb.Document.ContentStart, rtb.Document.ContentEnd);

MemoryStream ms = new MemoryStream(Content);

try

{

ms.Position = 0;

tr.Load(ms, System.Windows.DataFormats.XamlPackage);

}

catch(Exception)

{

ms.Position = 0;

tr.Load(ms, System.Windows.DataFormats.Xaml);

}

ms.Close();

}

  • Edited byBoanerge Tuesday, September 22, 2009 7:44 PMForgot a piece of code.
  •  
Boanerge

You can use google to search for other answers

Custom Search

More Threads

• Insert Into MySql Problem
• Custom Bitmap Effects
• ComboBox doesn't handle NotifyCollectionChanged, when bound in code to a Collection
• How do I include javascript code for XBAP Web application?
• texttrimming problem using binding
• Avalon equivalent of LinkLabel?
• Synchronization of scrollbar for grouped listbox and ungrouped listview
• Convert KeyPressed to character?
• Full trust XBAP with callback, is it possible with .net 3.5
• WPF/C# XBAP Serialization Error pulling Data Table from an ASP.NET Web Service