How do you insert a binding into the middle of a sentence of a TextBlock in WPF?

data-binding, wpf, xaml

Solution

You can use the StringFormat binding property in .NET 3.5 SP1:

<TextBlock Text="{Binding UserName,StringFormat='Welcome, \{0\}!'}" />

Note that you need to escape the curly braces in the string format with a backslash.

Update Yes, multiple values are also supported:

<TextBlock>
    <TextBlock.Text>
        <MultiBinding StringFormat="Welcome, {0} {1}!">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
        </MultiBinding>
    </TextBlock.Text>
</TextBlock>

Problem

I'm looking for something along these lines: ``` <TextBlock Grid.Column="1" Text="Welcome, {Binding UserName}!" /> ``` This will of course actually display the text "{Binding UserName}" to the user rather than decode it, but I know you can do something like this with ASP.NET, so I'm hoping there's a way to get this to work in WPF. I'm already aware that I could use an `IValueConverter`...I'm looking for something I can do purely in markup if possible. EDIT: Based on @Matt Hamilton's most excellent solution, I attempted to push the envelope and bind two values into the same `TextBlock` using a `MultiBinding`. Works like a charm: ``` <TextBlock Style="{StaticResource TextBlock_ValueStyle}" Grid.Column="1"> <TextBlock.Text> <MultiBinding StringFormat="{}Attempts: {0:G} of {1:G}"> <Binding Path="AttemptNumber" /> <Binding Path="AttemptCount" /> </MultiBinding> </TextBlock.Text> </TextBlock> ``` This produces: `Attempts: 1 of 4` (assuming `AttemptNumber = 1` and `AttemptCount = 4`). I also found this link helpful for figuring out which formats to place after the colon: http://msdn.microsoft.com/en-us/library/fbxft59x.aspx

Original source