'How to nest formatted strings in XAML?

Is it possible to nest formatted strings in XAML without creating a custom class?

Here is an example of what I want to achieve:

  • Format a string, e.g. "inner start {0} inner end".
  • Format the previous resultant string, e.g. "outer start {0} outer end".
  • Use the final string as the Text of a TextBlock.

As a concrete example, if "foo" was the string to be formatted, I would require the final string to be:

"outer start inner start foo inner end outer end"

I am able to format a single string with the following:

<TextBlock
Text="{Binding Source={x:Static res:Resources.Foo}, StringFormat={x:Static res:Resources.Bar}}" />

However, attempting to bind one Binding to another results in an error:

<TextBlock
Text="{Binding Source={Binding Source={x:Static res:Resources.Foo}, StringFormat={x:Static res:Resources.Bar}}, StringFormat={x:Static res:Resources.Baz}}" />

I think this could be achieved with an IMultiValueConverter, but I don't know if there is a simpler way.



Solution 1:[1]

I was able to achieve what I wanted with the following:

<Grid>
    <Grid.Resources>
        <ObjectDataProvider x:Key="FooBar"
                            ObjectType="{x:Type system:String}"
                            MethodName="Format">
            <ObjectDataProvider.MethodParameters>
                <x:Static Member="res:Resources.Foo" />
                <x:Static Member="res:Resources.Bar" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Grid.Resources>

    <TextBlock
        Text="{Binding Source={StaticResource FooBar}, StringFormat={x:Static res:Resources.Baz}}" />
</Grid>

In the above:

  • x is xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  • res is the .NET namespace (and assembly)
    • e.g. xmlns:res="clr-namespace:MyApp;assembly=MyApp"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James T