Add image inbetween text WPF RichTextBox

Viewed 38

I have a richTextBox that adds an image to the end of a document but I need it to add the image where the cursor is positioned within the RichTextBox. How can I go about this.

My XAML

<!-- XAML -->
<Grid>

    <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Button Click="insertImage_Click" Content="Add Image"
        Grid.Row="0"/>

    <RichTextBox BorderThickness="0" x:Name="RichTextBox"
        VerticalScrollBarVisibility="Auto" Grid.Row="1"/> 

</Grid>

And code behind

public partial class MainWindow : Window
{
    private OpenFileDialog ofdImage = new OpenFileDialog();
    Image insertImage;
    BlockUIContainer insertImageUIContainer;
    
    public MainWindow()
    {
        InitializeComponent();
    }

    private void insertImage_Click(object sender, RoutedEventArgs e)
    {
        if (ofdImage.ShowDialog() == true)
        {
            insertImage = new Image() { Source = new BitmapImage(new Uri(ofdImage.FileName)), Stretch = Stretch.Uniform, Width = RichTextBox.ActualWidth - 50 };
            insertImageUIContainer = new BlockUIContainer(insertImage);
            RichTextBox.Document.Blocks.Add(insertImageUIContainer); 
        }
    }
}
1 Answers

You can craete new paragraph at caret position and insert the image right there

Replace

RichTextBox.Document.Blocks.Add(insertImageUIContainer);

With

RichTextBox.CaretPosition.InsertParagraphBreak();
RichTextBox.Document.Blocks.InsertBefore(RichTextBox.CaretPosition.Paragraph, insertImageUIContainer);
Related