Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having hardcoded text with a binding in a TextBlock

In WPF, is there any way to have the Text property of a TextBlock to contain both hard coded text and a specific binding?

What I have in mind is something along the lines of the following (ofcourse, the below doesn't compile):

<TextBlock Text="Number of Fans: {Binding Artist.Fans.Count}"></TextBlock> 
like image 281
Andreas Grech Avatar asked Apr 25 '09 16:04

Andreas Grech


People also ask

Is TextBlock editable?

TextBlock is not editable.

What is a TextBlock?

textblock (plural textblocks) The block of pages making up a book, excluding the binding.

What is TextBlock WPF?

The TextBlock control provides flexible text support for UI scenarios that do not require more than one paragraph of text. It supports a number of properties that enable precise control of presentation, such as FontFamily, FontSize, FontWeight, TextEffects, and TextWrapping.


2 Answers

There is, if you are on .Net 3.5 SP1

<TextBlock Text="{Binding Path=Artist.Fans.Count,                   StringFormat='Number of Fans: {0}'}" /> 
like image 186
Scott Weinstein Avatar answered Sep 30 '22 19:09

Scott Weinstein


In using the above approach:

<TextBlock Text="{Binding Path="Artist.Fans.Count,                    StringFormat='Number of Fans: {0}'}" /> 

I found it somewhat restrictive in that I couldn't find a way to bold face inside the StringFormat nor could I use an apostrophe in the StringFormat.

Instead I went with this approach, which worked better for me:

<TextBlock TextWrapping="Wrap">     <Run>The value</Run>     <Run Text="{Binding Path=MyProperty1, Mode=OneWay}" FontWeight="Bold" />     <Run>was invalid. Please enter it with the format... </Run>     <LineBreak/><LineBreak/>     <Run>Here is another value in the program</Run>     <Run Text="{Binding Path=MyProperty2, Mode=OneWay}" FontWeight="Bold" /> </TextBlock>                     
like image 29
doogie Avatar answered Sep 30 '22 17:09

doogie