Xamarin.Forms 中 Label StringFormat 的本地化
Localization for Label StringFormat in Xamarin.Forms
在 xamarin 表单中,我可以将文本本地化为如下标签:
<Label Text="{x:Static resources:AppResources.Text}"/>
为资源命名空间:
<ContentView ...
xmlns:resources="clr-namespace:ProjectName.Resources;assembly=ProjectName">
我也可以绑定一些值并在标签中添加字符串格式:
<Label Text="{Binding Value, StringFormat='The value is: {0}' }"/>
问题是文本 值为: 未本地化。
谁可以同时执行绑定值和本地化 StringFormat?
找到了答案
我必须添加文本 值为:{0} 到资源文件。
我需要为翻译添加一个 IMarkupExtension。我将 class 添加到与资源文件相同的命名空间。
[ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension
{
private readonly CultureInfo _ci;
static readonly Lazy<ResourceManager> ResMgr = new Lazy<ResourceManager>(
() => new ResourceManager(typeof(AppResources).FullName, typeof(TranslateExtension).GetTypeInfo().Assembly));
public string Text { get; set; }
public TranslateExtension()
{
if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
{
_ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
}
}
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Text == null)
return string.Empty;
return ResMgr.Value.GetString(Text, _ci) ?? Text;
}
}
并像这样使用它:
<Label Text="{Binding Value, StringFormat={resources:Translate LabelTextTheValueIs}}" />
我能够只使用正常的本地化资源行而无需任何扩展名,如下所示:
Text="{Binding WireValue, StringFormat={x:Static resources:AppResources.PaymentDetailsLine3}}"
我的 AppResources.resx 中的 PaymentDetailsLine3 为:
<data
name="PaymentDetailsLine3"
xml:space="preserve">
<value>PaymentDetailsLine3 {0}</value>
在 xamarin 表单中,我可以将文本本地化为如下标签:
<Label Text="{x:Static resources:AppResources.Text}"/>
为资源命名空间:
<ContentView ...
xmlns:resources="clr-namespace:ProjectName.Resources;assembly=ProjectName">
我也可以绑定一些值并在标签中添加字符串格式:
<Label Text="{Binding Value, StringFormat='The value is: {0}' }"/>
问题是文本 值为: 未本地化。
谁可以同时执行绑定值和本地化 StringFormat?
我必须添加文本 值为:{0} 到资源文件。
我需要为翻译添加一个 IMarkupExtension。我将 class 添加到与资源文件相同的命名空间。
[ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension
{
private readonly CultureInfo _ci;
static readonly Lazy<ResourceManager> ResMgr = new Lazy<ResourceManager>(
() => new ResourceManager(typeof(AppResources).FullName, typeof(TranslateExtension).GetTypeInfo().Assembly));
public string Text { get; set; }
public TranslateExtension()
{
if (Device.RuntimePlatform == Device.iOS || Device.RuntimePlatform == Device.Android)
{
_ci = DependencyService.Get<ILocalize>().GetCurrentCultureInfo();
}
}
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Text == null)
return string.Empty;
return ResMgr.Value.GetString(Text, _ci) ?? Text;
}
}
并像这样使用它:
<Label Text="{Binding Value, StringFormat={resources:Translate LabelTextTheValueIs}}" />
我能够只使用正常的本地化资源行而无需任何扩展名,如下所示:
Text="{Binding WireValue, StringFormat={x:Static resources:AppResources.PaymentDetailsLine3}}"
我的 AppResources.resx 中的 PaymentDetailsLine3 为:
<data
name="PaymentDetailsLine3"
xml:space="preserve">
<value>PaymentDetailsLine3 {0}</value>