0

Say that I have a static text resource

public static string MainText = "Test: {0} Test2: {1}";

And I then want to use this text in WPF like this

<Label Content="x:Static ***.MainText" />

but bind two values to it, how do I do that?

2
  • I can add that I don't want to use Runs in a TextBlock since I want to keep the string as one string for translation. Commented Mar 15, 2016 at 13:21
  • You would use a Converter then. XAML can only go so far. And in YOur Binding you can also use StringFormat like so : <Label Content="{Binding INPCProperty, StringFormat}" Commented Mar 15, 2016 at 13:48

1 Answer 1

2

Here are two ways you can do it, one with a converter and one without.

"Text1" and "Text2" in the bindings are properties of the DataContext.

You will need to change the "MainText" to be a property:

public static string MainText { get; set; } = "Test: {0} Test2: {1}";

Without a converter:

<Label>
    <Label.Content>
        <TextBlock>
            <TextBlock.Text>
                <MultiBinding StringFormat="{x:Static local:MainWindow.MainText}">
                    <Binding Path="Text1" />
                    <Binding Path="Text2" />
                </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
    </Label.Content>
</Label>

With a converter:

<Label>
    <Label.Resources>
        <local:TextFormatConverter x:Key="TextFormatConverter" />
    </Label.Resources>
    <Label.Content>
        <MultiBinding Converter="{StaticResource TextFormatConverter}" ConverterParameter="{x:Static local:MainWindow.MainText}">
            <Binding Path="Text1" />
            <Binding Path="Text2" />
        </MultiBinding>
    </Label.Content>
</Label>

And the converter:

public class TextFormatConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string fmt = parameter as string;
        if (!string.IsNullOrWhiteSpace(fmt))
            return string.Format(fmt, values);
        return null;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I can't change it to a property because of the way we've set up our translation unfortunately. I wanted to see if there were some other solution than using a converter, but I'll just go for that then. Thanks :)
You could pass something else in as the parameter that identifies the text - like, "MainText" and then use reflection or whatever you have to find the string format somehow (project specific).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.