Manohar
Manohar

Reputation: 293

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?

Upvotes: 6

Views: 6205

Answers (3)

Gonzalo
Gonzalo

Reputation: 1876

In some frameworks you can use String Format as:

<TextBlock Text="{Binding Animals.Count, StringFormat='I have {0} animals.'}" />

For example in Avalonia: https://docs.avaloniaui.net/docs/basics/data/data-binding/data-binding-syntax

Upvotes: 0

Josh
Josh

Reputation: 69282

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.

Upvotes: 4

Matt Hamilton
Matt Hamilton

Reputation: 204259

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.

Upvotes: 13

Related Questions