How to pass Static Resource String to ConverterParameter in UWP
I am making a UWP project and I will not format the string using converter and Static resource String because the app is in multilingual languages.
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's the line in the Resource Strings.Xaml file:
<x:String x:Key="nbItems">You have {0} items...</x:String>
Here's the item I can't get past this formatter into:
<TextBlock Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter={StaticResource nbItems}, Mode=OneWay}"/>
It doesn't work, but if I like it, it works:
<TextBlock Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter='You have {0} items..', Mode=OneWay}"/>
Parameters are always zero in my converter, why doesn't it work?
+3
source to share
1 answer
It's not entirely accurate why the parameter is null, however I found a workaround. Move your lines to a resource file ( see here ).
Then change the parameter you are passing to the converter to String Name, for example:
<TextBlock Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter='FORMAT', Mode=OneWay}" />
Finally, modify your converter to load the resource using a parameter like this:
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 it helps.
+2
source to share