Используйте IMarkupExtension вместе со StringFormat - PullRequest
0 голосов
/ 26 июня 2018

Я использую TranslateExtension от Xamarin. Можно ли добавить StringFormat к звонку?

В настоящее время у меня есть

<Label Text="{i18n:Translate User}" />

но мне нужно что-то вроде этого

<Label Text="{i18n:Translate User, StringFormat='{0}:'}" />

Если я сделаю последнее, я получу

Xamarin.Forms.Xaml.XamlParseException: Невозможно назначить свойство "StringFormat": свойство не существует, или его нельзя назначить, или несовпадающий тип между значением и свойством

Я знаю, что мог бы добавить другой перевод с двоеточием, но было бы неплохо иметь другой вариант.

Ответы [ 3 ]

0 голосов
/ 27 июня 2018

Здесь я обновил образец Xamarin:

[ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension
{
    readonly CultureInfo ci = null;
    const string ResourceId = "UsingResxLocalization.Resx.AppResources";

    static readonly Lazy<ResourceManager> ResMgr = new Lazy<ResourceManager>(() => new ResourceManager(ResourceId, IntrospectionExtensions.GetTypeInfo(typeof(TranslateExtension)).Assembly));

    public string Text { get; set; }
    public string StringFormat {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;

        var translation = ResMgr.Value.GetString(Text, ci);
        if (translation == null)
        {
#if DEBUG
            throw new ArgumentException(
                string.Format("Key '{0}' was not found in resources '{1}' for culture '{2}'.", Text, ResourceId, ci.Name),
                "Text");
#else
            translation = Text; // HACK: returns the key, which GETS DISPLAYED TO THE USER
#endif
        }

        if(!string.IsNullOrWhitespace(StringFormat)
             return string.Format(StringFormat, translation);

        return translation;
    }
}
0 голосов
/ 03 июля 2018

Немного опоздал на вечеринку, но делая это со стандартным расширением и просто XAML, сделайте так:

<Label Text="{Binding YourDynamicValue, StringFormat={i18n:Translate KeyInResources}}"/>

Ваш перевод должен выглядеть примерно так: Static text {0}. Где {0} заменяется значением, к которому вы привязаны.

Проблема в том, что расширение Translate просто извлекает вашу строку из ресурсов и не имеет свойства StringFormat и т. Д. Но вы можете присвоить полученное значение ресурса StringFormat из Binding.

0 голосов
/ 27 июня 2018

Вы можете добавить свойство параметра в TranslateExtension.

Мой TranslateExtension выглядит следующим образом. Вы можете взять части Параметра и добавить его к одному из образца Xamarin.

[ContentProperty("Text")]
public class TranslateExtension : IMarkupExtension
{
    public string Text { get; set; }
    public string Parameter { get; set; }

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        try
        {
            if (Text == null)
                return null;

            var culture = new CultureInfo(CultureHelper.CurrentIsoLanguage);

            var result = LocalizationResources.ResourceManager.GetString(Text, culture);

            if (string.IsNullOrWhiteSpace(Parameter))
            {
                return string.IsNullOrWhiteSpace(result) ? "__TRANSLATE__" : result;
            }

            return string.IsNullOrWhiteSpace(result) ? "__TRANSLATE__" : string.Format(result, Parameter);
        }
        catch (Exception ex)
        {
            TinyInsights.TrackErrorAsync(ex);
            return "__TRANSLATE__";
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...