52

Can we concat two properties together in binding expression? If possible without converter or without writing two textblocks and setting them individually?

Nawaz
  • 353,942
  • 115
  • 666
  • 851
TCM
  • 16,780
  • 43
  • 156
  • 254
  • Take a look here http://stackoverflow.com/questions/541896/concatenate-strings-instead-of-using-a-stack-of-textblocks – NoWar Dec 08 '14 at 11:48

6 Answers6

117

If you want to show, say FirstName and LastName, in a single TextBlock, then you can do like this:

<TextBlock>
     <Run Text="{Binding FirstName}" />
     <Run Text="   " /> <!-- space -->
     <Run Text="{Binding LastName}" />
</TextBlock>

Now, the TextBlock's Text property will be "Sachin Tendulkar" and will be displayed if:

FirstName = Sachin
LastName  = Tendulkar
starball
  • 20,030
  • 7
  • 43
  • 238
Nawaz
  • 353,942
  • 115
  • 666
  • 851
31
<TextBlock.Text>
   <MultiBinding StringFormat="{}{0} , {1}">
     <Binding Path="data1" />
     <Binding Path="data2" />
    </MultiBinding>
</TextBlock.Text>

data1 and data2 are string properties which are binded.

Kiran k g
  • 946
  • 11
  • 19
19

Like alpha-mouse suggests MultiBinding won't work out of the box, but this guy has thrown something together that might help:

http://www.olsonsoft.com/blogs/stefanolson/post/Improvements-to-Silverlight-Multi-binding-support.aspx

If that seems a bit rogue, then maybe try putting a combined value property on your object as a helper for the Binding mechanism, like:

public string FullName {
   get { return this.FirstName + " " + this.LastName; }
}
Tom
  • 3,354
  • 1
  • 22
  • 25
7

It is possible in WPF with the help of MultiBinding and StringFormat. But not in Silverlight unfortunately.

alpha-mouse
  • 4,953
  • 24
  • 36
6

If you need to add any string, then try it. Here I add "%" after binding text in windows phone.

<TextBlock Text="{Binding Path=clouds.all, StringFormat=\{0\}%}"/>
reza.cse08
  • 5,938
  • 48
  • 39
4

You can add a new property with a getter that performs the concatenation.

Say you have FirstName and LastName properties. You can then define a Name property as follows:

public string Name { get { return FirstName + " " + LastName; } }

This will work well, but you should be aware that you cannot do two-way binding for a read-only property. Also you may want to implement property changed notification for the concatenated property in the setters for the source properties.

larsmoa
  • 12,604
  • 8
  • 62
  • 85
Rune Grimstad
  • 35,612
  • 10
  • 61
  • 76