UWP equivalent of Android's SpannableString with image inside

Apptacular Apps 386 Reputation points
2020-08-18T17:13:30.857+00:00

Is there a way to implement an image within a TextBlock rather than outside of it? Android has a feature called SpaanableStringBuilder which allows the user to create text with different appearances. Does UWP have something similar?

MyTextBlock.Text = "Google" + ? + "icon";

4uClG.png

Universal Windows Platform (UWP)
{count} votes

1 answer

Sort by: Most helpful
  1. Richard Zhang-MSFT 6,936 Reputation points
    2020-08-19T02:51:47.987+00:00

    Hello,

    Welcome to Microsoft Q&A.

    in UWP, RichTextBlock is needed for image and text mixing.

    With Xaml

    <RichTextBlock>
        <Paragraph>
            <Run Text="Something..."/>
            <InlineUIContainer>
                <Image Source="your_image_url" Width="20" Height="20"/>
            </InlineUIContainer>
            <Run Text="Something..."/>
        </Paragraph>
    </RichTextBlock>
    

    With Code

    var richTextBlock = new RichTextBlock();
    var para = new Paragraph();
    para.Inlines.Add(new Run() { Text = "Something..." });
    var imgContainer = new InlineUIContainer();
    var img = new Image();
    img.Source = new BitmapImage(new Uri("your_image_url"));
    imgContainer.Child = img;
    para.Inlines.Add(imgContainer);
    para.Inlines.Add(new Run() { Text = "Something..." });
    richTextBlock.Blocks.Add(para);
    

    Or you could write it this way, which more closely mirrors the XAML.

    var richTextBlock = new RichTextBlock()
    {
        Blocks = {
            new Paragraph {
                Inlines = {
                    new Run { Text = "Something" },
                    new InlineUIContainer {
                        Child = new Image {
                            Source = new BitmapImage(new Uri("your_image_url"))
                        }
                    },
                    new Run { Text = "Something..."}
                }
            }
        }
    };
    

    Thanks.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.