Using converter with Translate i18n in xamarin xaml

孤街浪徒 提交于 2019-12-12 04:08:45

问题


I want to add ":" at the end of string.

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

If I do this it works

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

This way does not work

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

I can't get this to work.


回答1:


Did you find a solution for this? Otherwise my solution might help you. I use a translation extention instead of the i18n package

in the extension set the ResourceId to your resx-File location add your custom property and implement the behavior after you got the translated text of the 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;
        }
    }
}

Then you can set the converter in the 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}}" />


来源:https://stackoverflow.com/questions/45632000/using-converter-with-translate-i18n-in-xamarin-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!