【问题标题】:Using converter with Translate i18n in xamarin xaml在 xamarin xaml 中使用转换器和 Translate i18n
【发布时间】:2017-08-11 09:45:33
【问题描述】:

我想在字符串末尾添加“:”。

public class StringToStringColonConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value + ":";
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}

如果我这样做,它会起作用

<Label Text="{Binding DocumentLabel, Converter={converter:StringToStringColonConverter}}" />

这种方式行不通

<Label Text="{i18n:Translate some_text_value, Converter={converter:StringToStringColonConverter}}" />

我无法让它工作。

【问题讨论】:

    标签: forms xaml xamarin internationalization


    【解决方案1】:

    您找到解决方案了吗?否则我的解决方案可能会对您有所帮助。 我使用翻译扩展而不是 i18n 包

    在扩展中将 ResourceId 设置为您的 resx-File 位置,添加您的自定义属性并在获得资源管理器的翻译文本后实现该行为

    using System;
    using System.Globalization;
    using System.Reflection;
    using System.Resources;
    using Xamarin.Forms;
    using Xamarin.Forms.Xaml;
    
    namespace Project.Utils
    {
        [ContentProperty("Text")]
        public class TranslateExtension : IMarkupExtension
        {
            const string ResourceId = "Project.Resources.AppResources";
            public string Text { get; set; }
    
            public IValueConverter Converter { get; set; }
    
            public object ProvideValue(IServiceProvider serviceProvider)
            {
                if (Text == null)
                    return null;
                ResourceManager resourceManager = new ResourceManager(ResourceId, typeof(TranslateExtension).GetTypeInfo().Assembly);
    
                string translatedText = resourceManager.GetString(Text, CultureInfo.CurrentCulture);
    
    
            if (this.Converter != null)
            {
                translatedText = Converter.Convert(translatedText, typeof(string), null, CultureInfo.CurrentCulture).ToString() ?? translatedText;
            }
    
                return translatedText;
            }
        }
    }
    

    然后你可以在 XAML 中设置转换器:

    xmlns:strings="clr-namespace:Project.Utils;assembly=Project"   
    
    <ContentPage.Resources>
        <ResourceDictionary>
            <converters:ColonSpaceConverter x:Key="ColonSpaceConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    
    <Label Text="{strings:Translate Money, Converter={StaticResource ColonSpaceConverter}}" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-14
      • 2019-09-21
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-06
      • 1970-01-01
      相关资源
      最近更新 更多