Concatenate strings instead of using a stack of TextBlocks Concatenate strings instead of using a stack of TextBlocks wpf wpf

Concatenate strings instead of using a stack of TextBlocks


There is StringFormat property (in .NET 3.5 SP1), which you probably can use. And usefull WPF binding cheat sheat can found here. If it doesn't help, you can allways write your own ValueConverter or custom property for your object.

Just checked, you can use StringFormat with multibinding. In your case code will be something like this:

<TextBlock>  <TextBlock.Text>    <MultiBinding StringFormat=" {0} - {1}">        <Binding Path="Number"/>        <Binding Path="Name"/>    </MultiBinding>  </TextBlock.Text></TextBlock>

I had to start format string with space, otherwise Visual Studio wouldn't build, but I think you will find way get around it :)

Edit
The space is needed in the StringFormat to keep the parser from treating {0} as an actual binding. Other alternatives:

<!-- use a space before the first format --><MultiBinding StringFormat=" {0} - {1}"><!-- escape the formats --><MultiBinding StringFormat="\{0\} - \{1\}"><!-- use {} before the first format --><MultiBinding StringFormat="{}{0} - {1}">


In case you want to concat a dynamic value with a static text, try this:

<TextBlock Text="{Binding IndividualSSN, StringFormat= '\{0\} (SSN)'}"/>

Displays: 234-334-5566 (SSN)


See the following example I used in my code using Run class:

        <TextBlock x:Name="..." Width="..." Height="..."            <Run Text="Area="/>            <Run Text="{Binding ...}"/>            <Run Text="sq.mm"/>            <LineBreak/>            <Run Text="Min Diameter="/>            <Run Text="{Binding...}"/>            <LineBreak/>            <Run Text="Max Diameter="/>            <Run Text="{Binding...}"/>        </TextBlock >