Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XAML Binding string concatenation

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?

like image 379
Manohar Avatar asked Dec 08 '22 04:12

Manohar


2 Answers

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.

like image 165
Matt Hamilton Avatar answered Jan 11 '23 08:01

Matt Hamilton


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.

like image 38
Josh Avatar answered Jan 11 '23 08:01

Josh