Reputation: 859
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
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;
}
}
<Label AutomationId="{local:Format LabelAutomationIdentifier, StringFormat='{0}_LabelName'}" />
Upvotes: 2