Reputation: 145
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?
Upvotes: 0
Views: 1202
Reputation: 4322
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();
}
}
Upvotes: 2