gpt4 book ai didi

c# - 如何将静态资源字符串传递给 UWP 中的 ConverterParameter

转载 作者:行者123 更新时间:2023-11-30 16:43:34 25 4
gpt4 key购买 nike

我正在做一个 UWP 项目,我不想使用转换器和静态资源字符串来格式化字符串,因为该应用程序使用多种语言。

这是我的转换器:

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();
}
}

这是我的 Resource Strings.Xaml 文件中的字符串:

<x:String x:Key="nbItems">You have {0} items...</x:String>

这里是我不想传递此格式化程序的元素:

<TextBlock  Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter={StaticResource nbItems}, Mode=OneWay}"/>

它不起作用,但如果我喜欢它,它就会起作用:

  <TextBlock  Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter='You have {0} items..', Mode=OneWay}"/>

我的转换器中的参数始终为 null,为什么它不起作用?

最佳答案

不确定为什么参数为空,但我想出了一个解决方法。将您的字符串移动到资源文件 ( see here )。

Resources file example

然后将传递给转换器的参数更改为字符串名称,如下所示:

<TextBlock  Text="{x:Bind NbItems, Converter={StaticResource StringFormatConverter}, ConverterParameter='FORMAT', Mode=OneWay}" />

最后更改您的转换器以使用如下参数加载资源:

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);
}

希望这对您有所帮助。

关于c# - 如何将静态资源字符串传递给 UWP 中的 ConverterParameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44756983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com