代码之家  ›  专栏  ›  技术社区  ›  Oscar Fraxedas

xamarin.forms中标签字符串格式的本地化

  •  5
  • Oscar Fraxedas  · 技术社区  · 7 年前


    <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?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Oscar Fraxedas    7 年前

    我发现答案在 Localizing XAML


    [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}}" />