Search code examples
xamarin.formsstring-formattingglobalizationresource-files

Xamarin Forms Cross Platform App Resource File with StringFormat


Is there a way to apply a StringFormat to a value from a Resource file. I basically want something like this:

Text="{localapp:Translate Port, StringFormat='{0}:'}"

Basically I don't want to put punctuation in the Resource file so I can reuse the value in more places in my app. Any help would be appreciated.


Solution

  • First we need to add a further property in our translate MarkupExtension to support StringFormat:

    [ContentProperty("Text")]
    public class TranslateExtension : IMarkupExtension
    {
        public string Text { get; set; }
    
        public string StringFormat { get; set; }
    
        public object ProvideValue(IServiceProvider serviceProvider)
        {
            if (string.IsNullOrEmpty(Text))
                return null;
    
            if (!string.IsNullOrEmpty(StringFormat))
                return string.Format(StringFormat, Resources.ResourceManager.GetString(Text));
    
            return Resources.ResourceManager.GetString(Text);
        }
    }
    

    Now we can use StringFormat in XAML like this:

    <Label Text="{utilities:Translate Port, StringFormat='{0}:'}"/>
    

    Now assuming we already defined a resourse such as Port="MyPort" , the output of the label would be:

    MyPort: