[英]How to pass Static Resource String to ConverterParameter in UWP
I m doing an UWP project and I wan't to format a string using a converter and Static resource String because the application is in mulitple languages. 我正在做一个UWP项目,我不想使用转换器和静态资源字符串格式化字符串,因为应用程序是多种语言。
Here is my converter : 这是我的转换器:
public class StringFormatConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value == null)
return null;
if (parameter == null)
return value;
return string.Format((string)parameter, value);
}
public object ConvertBack(object value, Type targetType, object parameter,
string language)
{
throw new NotImplementedException();
}
}
Here the string in my Resource Strings.Xaml file : 这是我的Resource Strings.Xaml文件中的字符串:
<x:String x:Key="nbItems">You have {0} items...</x:String>
Here the element where I wan't to pass this formatter : 这里是我不想通过这个格式化程序的元素:
<TextBlock Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter={StaticResource nbItems}, Mode=OneWay}"/>
It's not working but if I do like this it works : 它不起作用,但如果我这样做,它的工作原理:
<TextBlock Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter='You have {0} items..', Mode=OneWay}"/>
The parameters is always null in my converter, why it's not working ? 我的转换器中的参数始终为空,为什么它不起作用?
Not exactly certain why the parameter is null, however I have come up with a workaround. 不完全确定参数为空的原因,但我提出了一个解决方法。 Move your strings into a Resource file ( see here ).
将您的字符串移动到资源文件中( 请参阅此处 )。
Then change the parameter you pass to your converter to the String Name, like so: 然后将传递给转换器的参数更改为String Name,如下所示:
<TextBlock Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter='FORMAT', Mode=OneWay}" />
Finally change your converter to load the the resource using the parameter like so: 最后更改转换器以使用如下参数加载资源:
public object Convert(object value, Type targetType, object parameter, string language) {
if (value == null)
return null;
var loader = new Windows.ApplicationModel.Resources.ResourceLoader();
var str = loader.GetString((string)parameter);
return string.Format(str, value);
}
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.