views:

50

answers:

4

Hello developers. I have some class with properties firstName and lastName. I want bind TextBlock to concatanation of this two properties. I know that I can create third property that will be return concatanation of these properties. But I dont want to use this approach. Is it possible to Bind TextBlock to two properties. and also I dont want create composite userControl.

A: 

I'm not sure if it's possible to bind to two properties, but there is not reason you cannot create two TextBlocks right?

<TextBlock Text="{Binding firstName}"/> <TextBlock Text="{Binding lastName}"/>
Amry
I can do this. But have a lot of textBlock on my form (about 200). It will boring to do this.
Polaris
If it's that many, it will be boring anyways even if you can pack all the bindings into one TextBlock. Might as well come up with a code that will loop the whole thing and create the TextBlocks for for you. I'm not really that familiar with WPF, I would also be interested to know if there's any other better alternative to do this. +1 for this question.
Amry
+2  A: 

You could use multibinding, but I guess that you have to code your way out of the concatanation. Here is an example: Multibinding

Oppermann
My shame. I dont know about Multibindings. Interesting approach.
Polaris
A: 

use either MultiBinding or Converter (if complex operation is there)

Kishore Kumar
+3  A: 

In .NET 3.5SP1, Microsoft added StringFormat to bindings. This makes it much easier. See Lester's blog post for an example. In your case:

<TextBox>
  <TextBox.Text>
    <MultiBinding StringFormat="{0} {1}">
      <Binding Path="FirstName" />
      <Binding Path="LastName"/>
    </MultiBinding>
  </TextBox.Text>
</TextBox>

or

<TextBox>
  <TextBox.Text>
    <MultiBinding StringFormat="{1}, {0}">
      <Binding Path="FirstName" />
      <Binding Path="LastName"/>
    </MultiBinding>
  </TextBox.Text>
</TextBox>
Daniel Rose