Hello, I have an object, say Person, which has First Name and Last Name properties. on my WPF UI, I have a Label which needs to bind to the full name. how can i concatinate in xaml. . i dont want to create another readonly property like FullName{get FisrtName+""+LastName} . can we do this in XAML?. Thanks, Rey.
A couple of options:
Option 1: Single TextBlock (or Label) with a MultiBinding:
<TextBlock>
<TextBlock.Text>
<MultiBinding StringFormat="{}{0} {1}">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
Option 2: Multiple TextBlocks (or Labels) in a horizontal StackPanel:
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding FirstName}" />
<TextBlock Text=" " />
<TextBlock Text="{Binding LastName}" />
</StackPanel>
Personally I'd go with option 1.
I love the MultiBinding approach Matt described. However, I should also note that depending on the architecture of your application creating the FullName property that you didn't want to create is an equally valid (and arguably a more desirable) choice.
If you were using Model-View-ViewModel, you would have a ViewModel that would expose a FullName property for the sole purpose of binding it to the view.
For example, if the requirements suddenly changed such that you needed to be able to format it as First + Last or Last, First depending on a configuration setting it'd be much easier to do on the ViewModel. Likewise, writing a unit test to validate that a change to FirstName or LastName also results in an appropriate change in FullName is not practical using the straight XAML approach.
But like I said it all depends on the architecture of your application.