WPF の TextBlock 内に画像を含める方法

TextBlock の中身を少し工夫するとき、たいていのケースでは Run を利用すると思います。
ただ、画像を含めたい場合にはそういうわけにはいきません。

そういうシーンはそんなにないのでは? と思いきや、WPF でカラーの絵文字を表示したいというときには、画像を利用する必要が発生します。

こういうときには UIElement を埋め込むことが出来る InlineUIContainer を利用すると実現できます。

InlineUIContainer Class (System.Windows.Documents)
https://msdn.microsoft.com/en-us/library/system.windows.documents.inlineuicontainer(v=vs.110).aspx

XAML

<Window x:Class="ImageInTextBlock.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel Background="LightBlue">
        <TextBlock Margin="5"
                   Background="White"
                   FontSize="20">
            <Run>ナナチはかわいいですね</Run>
            <InlineUIContainer>
                <Image Width="15"
                       Source="https://emojipedia-us.s3.amazonaws.com/thumbs/160/twitter/103/smiling-face-with-halo_1f607.png" />
            </InlineUIContainer>
        </TextBlock>
    </StackPanel>
</Window>

見栄え調整のため余計なものが若干あります。
ここでの本質は、InlineUIContainer > Image という入れ子構造になっているポイントです。

実際の表示

f:id:bps_tomoya:20171004002305p:plain

おわり。