【问题标题】:Localization for Label StringFormat in Xamarin.FormsXamarin.Forms 中标签 StringFormat 的本地化
【发布时间】:2018-11-22 07:13:16
【问题描述】:

在 xamarin 表单中,我可以将文本本地化为以下标签:
<Label Text="{x:Static resources:AppResources.Text}"/>

带有资源的命名空间:
<ContentView ... xmlns:resources="clr-namespace:ProjectName.Resources;assembly=ProjectName">

我也可以绑定一些值,给标签添加字符串格式:
&lt;Label Text="{Binding Value, StringFormat='The value is: {0}' }"/&gt;

问题是文本值是:没有本地化。

谁可以同时做,绑定一个值并本地化 StringFormat?

【问题讨论】:

    标签: data-binding xamarin.forms localization label string-formatting


    【解决方案1】:

    我在Localizing XAML找到了答案

    我必须在资源文件中添加文本值为:{0}。
    我需要为翻译添加一个 IMarkupExtension。我将该类添加到与资源文件相同的命名空间中。

    [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;
        }
    }
    

    并像这样使用它:

    &lt;Label Text="{Binding Value, StringFormat={resources:Translate LabelTextTheValueIs}}" /&gt;

    【讨论】:

      【解决方案2】:

      我能够只使用普通的本地化资源行而无需任何扩展,如下所示:

      Text="{Binding WireValue, StringFormat={x:Static resources:AppResources.PaymentDetailsLine3}}"
      

      PaymentDetailsLine3 在我的 AppResources.resx 中的位置为:

         <data
        name="PaymentDetailsLine3"
        xml:space="preserve">
        <value>PaymentDetailsLine3 {0}</value>
      

      【讨论】:

        猜你喜欢
        • 2010-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-04-19
        • 2011-09-19
        • 1970-01-01
        • 2015-12-29
        • 2013-07-10
        相关资源
        最近更新 更多