I have an object Person
, which has FirstName
and LastName
properties.
In my WPF UI, I have a Label
which needs to bind to the full name:
<Label Binding="{Binding FullName}" />
I don't want to create another read-only property like:
public string FullName { get { return FirstName + " " + LastName; } }
How can I concatenate these two properties in XAML?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With