简体   繁体   中英

Adding an image inside a RichTextBox WPF

I'm trying to add a static image inside a RichTextBox based on the selection of a ListBox item. I'm able to achieve the functionality of loading the image but the image doesn't occupy the entire size of the RichTextBox . I looked at MSDN documentation for any property I could set but couldn't find any that suits my need.

I've posted a sample code snippet to add an image to a RichTextBox .

<Window x:Class="ImageDepth.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <RichTextBox HorizontalAlignment="Center" Height="100" VerticalAlignment="Center" Width="100" BorderBrush="Gray">
        <FlowDocument>
            <BlockUIContainer>
                <Image Source="C:\Temp\Penguins.jpg"/>
            </BlockUIContainer>                
        </FlowDocument>
    </RichTextBox>
</Grid>

Am I missing something here or is there a simpler way to achieve this?

Edit: I tried setting the Height and Width of the Image to that of the RichTextBox but it covers about 80% of the RichTextBox . Also, I had to remove the Stretch property of the Image since it distorts the image slightly even though setting the property makes the image cover about 90% of the area.

You have to bind Height and Width of Image to ActualHeight and ActualWidth of RichTextBox.

<Image Source="C:\Temp\Penguins.jpg"
       Width="{Binding ActualWidth, RelativeSource={RelativeSource
                               Mode=FindAncestor, AncestorType=RichTextBox}}"
       Height="{Binding ActualHeight, RelativeSource={RelativeSource
                             Mode=FindAncestor, AncestorType=RichTextBox}}"/>

UPDATE

There seems internal padding of RichTextBox. You can set that to negative value to remove that padding.

<RichTexBox Padding="-5,-2,-5,-2"> // It reads Left, Top, Right, Bottom
   ....
</RichTexBox>

Change -5,-2,-5,-2 to desired value which seems fit for you.

Try this:

<Window x:Class="ImageDepth.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <RichTextBox HorizontalAlignment="Center" Height="100" VerticalAlignment="Center" Width="100" BorderBrush="Gray">
        <FlowDocument>
            <BlockUIContainer>
                <Image Height="100" Width="100" Source="C:\Temp\Penguins.jpg" Stretch="Fill"/>
            </BlockUIContainer>                
        </FlowDocument>
    </RichTextBox>
</Grid>

This will tell your image to fill the entire RichTextBox .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM