在xamarin xaml中使用带有Translate i18n的转换器

时间:2017-08-11 09:45:33

标签: forms xaml xamarin internationalization

我想添加":"在字符串的末尾。

Map<Boolean,Integer> result = feature.stream()
            .map(Map.Entry::getValue)
            .collect(Collectors.groupingBy(
                Function.identity(), 
                Collectors.collectingAndThen(Collectors.counting(), Long::intValue)));

如果我这样做就行了

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

我无法让它发挥作用。

1 个答案:

答案 0 :(得分:1)

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

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

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