Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display images in TextBlock (WPF)

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

like image 890
lacop Avatar asked Apr 07 '09 19:04

lacop


4 Answers

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>
like image 173
Schulzer Avatar answered Nov 07 '22 00:11

Schulzer


The Content of a TextBlock is always just a series of Inlines, so you should use the InlineUIContainer. You can insert this container as one of the Inlines in your TextBlock wherever you want an Image to appear, alternating with text Runs. You could parse a message and at the same time keep adding the tokens (either text or images) that you find to the Inlines collection of the TextBlock.

like image 28
PeterAllenWebb Avatar answered Nov 07 '22 02:11

PeterAllenWebb


If you want the Images actually inside the text (like an emoticon), then you are going to have to do some work. This sounds like one of the few times I would actually want a User Control, the point of which would be one that scans the Text looking for emoticon values and building a Data Template on the fly.

Remember that anything you can do in XAML you can do in code, so the code I'm thinking of would follow this general idea:

  1. Scan text for emoticon values and create a list of values for data elements.
  2. Create a DockPanel.
  3. Foreach element in the List, add either a TextBlock or an Image (based on value).
  4. Set this.Content to the DockPanel.

I think something like this is actually what you are looking for, but if you want just an Image, then the ValueConverter suggestion would work.

like image 1
Joel Cochran Avatar answered Nov 07 '22 01:11

Joel Cochran


You could use a value converter to convert the text to another type which has a list of segments which are composed of either text or the smiley face (in the order in which they appear).

Then, you can use a data template to bind to that new type and display the text and smiley faces appropriately.

like image 1
casperOne Avatar answered Nov 07 '22 02:11

casperOne