views:

142

answers:

3

I'd really like to be able to do some manipulation to the stuff I'm binding. Similar to being able to call String.Format() in a <%#%> tag in ASP.Net.

For example, assuming this is the type I'm binding:

class User {
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public int Age { get; set; }
}

and this is the Label I'm binding it to (I know this won't work):

<Label Name="someLabel" Content="{Binding LastName+,+FirstName+ +Age}")/>

Where I want the outcome to be: Smith,John 32

+3  A: 

Try this:

class User {
   //...
   public string NameAndAge
   {
      get
      {
         return string.Format("{0}, {1} {2}",LastName , FirstName , Age);
      };
   }
}



<Label Name="someLabel" Content="{Binding NameAndAge}")/>
Marcel Benthin
+1 Oh geez... that's a good idea, I didn't think of that. lol
blesh
That's what SO is for :)
Marcel Benthin
A: 

I ended up doing this:

<TextBlock>
    <TextBlock Text="{Binding LastName}"/><Run>,</Run>
    <TextBlock Text="{Binding FirstName}"/>
    <TextBlock Text="{Binding Age}"/>
</TextBlock>

Figured I'd leave that answer in here for anyone that has the same problem I did.

I'm still curious to see if anyone else knows a more clever way to accomplish this, as this seems a little hokey.

blesh
+6  A: 

Multibinding + StringFormat (3.5 sp1)!!!!!

<TextBlock>
<TextBlock.Text>
    <MultiBinding StringFormat="{0}, {1} {2}">
      <Binding Path="LastName"/>
      <Binding Path="FirstName"/>
      <Binding Path="Age"/>
    </MultiBinding>
</TextBlock.Text>
</TextBlock>
Will
You might have to escape the brackets... "{}{0}, {1} {2}"
Will
This will make it easier (or at least more "natural") to implement property change notification (aka `INotifyPropertyChanged`)
Thomas Dufour
Now that's REALLY cool! I didn't know about that. I'm actually sorry I wiki'ed this question. I only did so because I thought I answered it myself. This is exactly what I wanted to do.
blesh