Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding text to a bound TextBlock

I would like to prepend a text in a data-bound text block:

<TextBlock Text="{Binding Title}" /> 

The text that is shown is:

"My title" 

What I want to be shown is:

This is "My title" 
like image 927
Rhys Avatar asked Aug 20 '11 09:08

Rhys


2 Answers

You can use the StringFormat property of the binding:

 <TextBlock Text="{Binding Title, StringFormat=This is {0}}"></TextBlock>  

Check out this blog post for more information: WPF String.Format in XAML with the StringFormat attribute.

like image 145
Shebin Avatar answered Sep 20 '22 03:09

Shebin


If you want to do it in the binding:

<TextBlock Foreground="#FFC8AB14" FontSize="28">     <TextBlock.Text>         <Binding Path="Title">             <Binding.StringFormat>                 This is "{0}"             </Binding.StringFormat>         </Binding>     </TextBlock.Text> </TextBlock> 

Element syntax required to escape quotes. If the quotes where just to mark the inserted text and should not appear in the output it is much easier of course:

<TextBlock Text="{Binding Title, StringFormat={}This is {0}}" Foreground="#FFC8AB14" FontSize="28"> 
like image 23
H.B. Avatar answered Sep 24 '22 03:09

H.B.