Anoop
Anoop

Reputation: 859

How to Append text to static resource in Xamarin.Forms?

I have my resource like this.

<ContentView.Resources>
    <ResourceDictionary>
        <x:String x:Key="LabelAutomationIdentifier">LBL_PD_L_PLV_LV_</x:String>
    </ResourceDictionary>
</ContentView.Resources>

I need to use this resource in the AutomationId property of Label like this

<Label AutomationId="{StaticResource LabelAutomationIdentifier} + LabelName" />

But, this is not correct. I tried multiple ways but no luck.

I tried,

<Label AutomationId="{Binding Source={StaticResource LabelAutomationIdentifier}, StringFormat='{}{0}LabelName'}" />

also

<Label AutomationId="{StaticResource LabelAutomationIdentifier, StringFormat='{0}LabelName'}" />

Upvotes: 3

Views: 2344

Answers (1)

Sharada
Sharada

Reputation: 13601

Had it been that the AutomationId was a bindable property - <Label AutomationId="{Binding Source={StaticResource LabelAutomationIdentifier}, StringFormat='{}{0}LabelName'}" /> would have worked just fine.

But it is not, and I believe that is the reason the Binding won't work in this case. Also, StaticResource doesn't have a StringFormat property to work with here, so the second option fails.

You can, however extend StaticResource extension to create a custom-markup extension to add formatting support.

[ContentProperty("StaticResourceKey")]
public class FormatExtension : IMarkupExtension
{
    public string StringFormat { get; set; }
    public string StaticResourceKey { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        string toReturn = null;
        if (serviceProvider == null)
            throw new ArgumentNullException(nameof(serviceProvider));

        if (StaticResourceKey != null)
        {
            var staticResourceExtension = new StaticResourceExtension { Key = StaticResourceKey };

            toReturn = (string)staticResourceExtension.ProvideValue(serviceProvider);
            if (!string.IsNullOrEmpty(StringFormat))
                toReturn = string.Format(StringFormat, toReturn);
        }

        return toReturn;
    }
}

Sample Usage

<Label AutomationId="{local:Format LabelAutomationIdentifier, StringFormat='{0}_LabelName'}" />

Upvotes: 2

Related Questions