Xamarin.Forms 中标签 StringFormat 的本地化 [英] Localization for Label StringFormat in Xamarin.Forms
问题描述
在 xamarin 表单中,我可以本地化标签中的文本,例如:<Label Text="{x:Static resources:AppResources.Text}"/>
In xamarin forms I can localize the text in a label like:
<Label Text="{x:Static resources:AppResources.Text}"/>
为资源命名空间:
我还可以绑定一些值并为标签添加字符串格式:<Label Text="{Binding Value, StringFormat='The value is: {0}' }"/>
I can also bind some value and add a string format to the label:
<Label Text="{Binding Value, StringFormat='The value is: {0}' }"/>
问题在于文本值为:未本地化.
The problem is that the text The value is: is not localized.
我可以同时绑定一个值和本地化 StringFormat 两者吗?
Who can I do both, bind a value and localize the StringFormat?
推荐答案
我在 本地化 XAML
我必须将文本值是:{0} 添加到资源文件中.
我需要为翻译添加一个 IMarkupExtension.我将该类添加到与资源文件相同的命名空间中.
I had to add the text The value is: {0} to the resource file.
I needed to add an IMarkupExtension for the translation. I added the class to the same namespace as the resource file.
[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}}"/>
这篇关于Xamarin.Forms 中标签 StringFormat 的本地化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!