Joe*_*zer 1 globalization resources xaml xamarin
我正在使用 Xamarin 编写一个移动应用程序,我有一个名为 Strings 的静态类,用于包装我的 RESX 资源。我想使用 x:Static 绑定到我的 XAML 文件中的这些。如果我有一个要绑定到的静态属性的静态类,这将起作用。
我删掉了一些评论和其他非必要的部分,但它基本上是这样的:
namespace MyCompany.Resources
{
public static partial class Strings
{
public static string LabelUsername { get { return Resources.LabelUsername; } }
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我的 XAML 中,我像这样绑定到它:
<Entry Placeholder="{x:Static resources:Strings.LabelUsername}"
其中资源定义为
xmlns:resources="clr-namespace:MyCompany.Resources;assembly=MyCompany"
这一切正常。当我向字符串添加嵌套类时,它会崩溃。这个类看起来像这样:
namespace MyCompany.Resources
{
public static partial class Strings
{
public static partial class Label
{
public static string Username { get { return Resources.Label_Username; } }
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我这样做,那么我会像这样在我的 XAML 中绑定到它:
<Entry Placeholder="{x:Static resources:Strings.Label.Username}"
Run Code Online (Sandbox Code Playgroud)
注意在“resources:”之后我们现在有三个级别(Strings.Label.Username)。这似乎是失败的原因。当我这样做时,我收到编译错误: Type Strings.Label not found in xmlns clr-namespace:MyCompany.Resources;assembly=MyCompany
此外,我可以从我的 ViewModel 中很好地访问嵌套类及其属性。有什么办法可以从 XAML 进行这项工作吗?我知道我可以绑定到 VM 中的一个变量,然后引用 Strings.Label.Username,但我不想为每个资源绑定都这样做。
小智 6
绑定中的静态属性名称应为
Strings+LabelUsername.Username
Run Code Online (Sandbox Code Playgroud)
您不仅有拼写错误,而且还尝试使用点表示法来引用嵌套类,但这是行不通的。
绑定使用标准的 .net 反射符号来按名称引用属性和类(它们要么在字符串上使用解析器,要么直接使用反射,无法检查代码库)。嵌套类名使用 a+来分隔包含类名和内部类名。您可以在此处阅读更多相关信息: