【问题标题】:How to Append text to static resource in Xamarin.Forms?如何将文本附加到 Xamarin.Forms 中的静态资源?
【发布时间】:2017-11-18 02:09:09
【问题描述】:

我有这样的资源。

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

我需要像这样在Label的AutomationId属性中使用这个资源

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

但是,这是不正确的。我尝试了多种方法,但没有运气。

我试过了,

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

还有

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

【问题讨论】:

标签: xaml xamarin xamarin.forms staticresource


【解决方案1】:

如果 AutomationId 是一个可绑定的属性 - &lt;Label AutomationId="{Binding Source={StaticResource LabelAutomationIdentifier}, StringFormat='{}{0}LabelName'}" /&gt; 本来可以正常工作的。

但事实并非如此,我相信这就是Binding 在这种情况下不起作用的原因。此外,StaticResource 没有可在此处使用的 StringFormat 属性,因此第二个选项失败。

但是,您可以扩展 StaticResource 扩展以创建自定义标记扩展以添加格式支持。

[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'}" />

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-13
  • 1970-01-01
  • 1970-01-01
  • 2014-08-11
  • 1970-01-01
相关资源
最近更新 更多