您在这里有三个选择。
第一个选项:修改视图模型以公开格式化字符串并绑定到该字符串。
public string CountFormatted {
get {
return String.Format(AppResources.TextResource, Count);
}
}
<TextBlock Text="{Binding Path=CountFormatted}" />
第二个选择: 做一个转换器MyCountConverter
public class MyCountConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value == null)
return value;
return String.Format(culture, AppResources.TextResource, value);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
<phone:PhoneApplicationPage.Resources>
<local:MyCountConverter x:Key="MyCountConverter"/>
</phone:PhoneApplicationPage.Resources>
...
<TextBlock Text="{Binding Count, Converter={StaticResource MyCountConverter}}"/>
第三种选择:使用可绑定转换器参数,以便您可以制作一个通用的 StringFormat 转换器,您可以在其中实际绑定转换器参数。 Windows Phone 中不支持开箱即用,但仍然可行。查看this http://www.shujaat.net/2011/02/wpf-binding-converter-parameter.html有关如何完成此操作的链接。
但是,除非您使用资源来支持多种语言,否则将格式作为纯字符串传递给转换器要容易得多。
<TextBlock Text="{Binding Count,
Converter={StaticResource StringFormatConverter},
ConverterParameter='Text: {0}'}" />
你必须做一个StringFormatConverter
在这种情况下使用该参数的转换器。
Edit:
关于第三个选项,您可以使用IMultiValueConverter
在上面的链接中实现你想要的。您可以添加以下转换器:
public class StringFormatConverter: IMultiValueConverter {
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
var param = values[0].ToString();
var format = values[1].ToString();
return String.Format(culture, format, param);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
<TextBlock Text="{Binding ElementName=MultiBinder, Path=Output}" />
<binding:MultiBinding x:Name="MultiBinder" Converter="{StaticResource StringFormatConverter}"
NumberOfInputs="2"
Input1="{Binding Path=Count, Mode=TwoWay}"
Input2="{Binding Path=LocalizedResources.TextResource, Source={StaticResource LocalizedStrings}}" />
我不知道这是否值得付出努力。