Alex Rivera | Logout

Display images in TextBlock (WPF)

Asked 2009-04-07T19:26:18.990
15

I'm working on a simple chat application. Currently the messages are binded to a custom-styled listbox like this (simplified XAML):

<ListBox ItemsSource="{Binding MessageCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Text}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Now I would like to be able to put images (like graphical smileys) into the displayed message text. Is there any way to achieve this using TextBlock (or any other standart component) or do I need to use some special control for this?

Thanks in advance

Edit
Report

2 Answers

58

Just use the InlineUIContainer.

<TextBlock TextWrapping="Wrap">
    <Run>Some text.</Run>
    <InlineUIContainer>
        <Image Source="http://sstatic.net/stackoverflow/img/apple-touch-icon.png" Height="20"></Image>
    </InlineUIContainer>
    <Run>Some more text.</Run>
</TextBlock>
answered 2011-04-07T23:42:23.323
1

I also encountered this problem recently and I overcome this by

Creating an ListBox ItemTemplate containing an ItemsControl that has a WrapPanel in the ItemsPanelTemplate and then binding my string to the ItemsSource of the ItemsControl with a IValueConverter that houses all the logic.

Split out your words and query/search your emoticons strings, hyperlinks etc and create your TextBlock, Image, Hyperlink, Button elements and set your values and event handles.

In the function create a List<UIElement> and populate the List with the controls you have generated and return the List as the object in the Convert function of the IValueConverter.

Because you have the WrapPanel in there you get your wrapping done.

answered 2012-04-12T15:49:44.207

Your Answer