如何构建字符串以动态访问.resx资源
问题描述:
我想知道如何动态构建字符串以引用我的Resources.resx文件中的字符串?我基本上想在XAML中执行以下等效操作:如何构建字符串以动态访问.resx资源
这样我就可以获得标题为ToyBlockName
或ToyBallName
的资源,它应该来自resx,因此可以在必要时进行翻译。然后我希望将这些单独的字符串插入其他字符串的格式中。有很多字符串使用这些名字,所以如果我可以替换单个单词而不是每种玩具的每个字符串的版本,那将是最好的。
一些示例字符串是The {0} comes in a box.
,The {0} costs only a few dollars.
本质上试图做到这一点在XAML:
String.Format(Properties.Resources.Default["ToyComesInBox"],
Properties.Resources.Default["Toy" + Constants.ToyName + "Name"]);
(其中ToyName = “阻止” 或者 “球” 等)
有一种在XAML中实现这一点的方法,还是有其他一些我没有想到的方法?
答
我不认为只用XAML就可以做到这一点,但我们正在使用converter/s来完成。它可能会变得非常混乱,但是如果你设计的比我更好,它就会有更多的潜力,并且它使得代码更好的IMO。
public class LocalizationConverter : IValueConverter
{
public object Convert(
object value,
Type targetType,
object parameter,
string language)
{
string valueString = value as string;
var paramString = parameter as string;
//so here you have the value of your binding in the value string
//and if it's empty (because you don't want to use the bound value
//you're setting the value string to be the param string
if (string.IsNullOrWhiteSpace(valueString))
{
valueString = paramString;
}
//if value string (formerly your param string is empty just return
//there is no value to be found
if (string.IsNullOrWhiteSpace(valueString))
{
return null;
}
//now the fun starts :) ,I pass values with small command and
//separator symbol to be able to parse my parameters
//something like this:
//if (paramString.StartsWith("AddAfter|"))
//{
// var valToAppend = paramString.Substring("AddAfter|".Length);
// return Strings.Get(Strings.Get(valToAppend + valueString));
//}
//and this basically does -> append the given parameter string after
//the part with the command to the value that comes from the binding
//and then uses the resulting string from res dictionary
//So you could do something like passing "ToyType|Block" or you can
//pass something in the value like Block and then in the parameters
//have description ToyType or even pass not string object and get
//what you want from it like
//if(value is ToyType)
//{
// return StringsGet((value as ToyType).Name)
//}
//Your parsing logic HERE
//This is how we get strings from resources in our project
//that you already know how to do
return Strings.Get(valueString);
}
public object ConvertBack(
object value,
Type targetType,
object parameter,
string language)
{
throw new NotImplementedException();
}
}
使用
定义的资源(页或全球)
<converters:LocalizationConverter x:Key="Loc" />
使用XAML中
值仅从参数(在这种情况下字符串)
<TextBlock Text="{Binding
Converter={StaticResource Loc},
ConverterParameter=ToyBlockName}" />
或者只从绑定变量的值(可以是任何类型的对象)从绑定的变量+复杂的参数
<TextBlock Text="{Binding ToyBlockNameBoundValue
Converter={StaticResource Loc}}" />
或价值可能被解析
<TextBlock Text="{Binding SomeBoundValue
Converter={StaticResource Loc},
ConverterParameter=SomeMoreComplex|Parameter}" />
为什么这样做在XAML,如果你有一个解决方案在C#中? –
只是试图将代码保留在代码隐藏之外。我可以在初始化Windows /控件时设置这些字符串,但我很想知道是否有纯XAML方法来实现它。 – densegoo