Having hardcoded text with a binding in a TextBlock

41,880

Solution 1

There is, if you are on .Net 3.5 SP1

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

Solution 2

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>                    

Solution 3

Use Binding.StringFormat:

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

Solution 4

Here the binding value(clouds.all) is added with "%". You can add any value you want after "\{0\}".

 <TextBlock Text="{Binding Path=clouds.all, StringFormat=\{0\}%}"/>
Share:
41,880
Andreas Grech
Author by

Andreas Grech

+++++[&gt;+++++[&gt;++++&lt;-]&lt;-]&gt;&gt;+++.--..++++++. Contactable at $(echo qernfterpu#tznvy?pbz | tr ?a-z# .n-za-m@)

Updated on January 31, 2020

Comments

  • Andreas Grech
    Andreas Grech over 4 years

    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>
    
  • Nathan Tuggy
    Nathan Tuggy over 8 years
    Could you please edit in an explanation of why this code answers the question? Code-only answers are discouraged, because they don't teach the solution.
  • reza.cse08
    reza.cse08 over 8 years
    @Nathan I edit my answer. Is it helpful now? Thank for your advice.
  • Johan Aspeling
    Johan Aspeling almost 8 years
    Is this possible to use multiple outputs, similar to args[] in the string.Format([1], [2], [3],...[n])?
  • BenKoshy
    BenKoshy almost 7 years
    hi Danko - would you know how to make it work with property element syntax?
  • WeSam Abdallah
    WeSam Abdallah over 6 years
    it's missing escaping \{0\}
  • CAD bloke
    CAD bloke over 4 years
    ... or use 2 bindings in the same TextBlock