xamlbindingstring-concatenation

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?


Solution

  • 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.