xaml - 如何将文本附加到 Xamarin.Forms 中的静态资源?

标签 xaml xamarin xamarin.forms staticresource

我有这样的资源。

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

最佳答案

如果AutomationId是一个可绑定(bind)属性 - <Label AutomationId="{Binding Source={StaticResource LabelAutomationIdentifier}, StringFormat='{}{0}LabelName'}" />会工作得很好。

但事实并非如此,我相信这就是 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'}" />

关于xaml - 如何将文本附加到 Xamarin.Forms 中的静态资源?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47350470/

相关文章:

c# - 使用带有偏移的 RotateTransform 问题旋转图像

xamarin - 更新xamarin后android类库资源出现问题

android - Xamarin 的 HelloWorld 错误

c# - Windows 10 移动版不遵守 KeyboardFlags.None

xamarin - 如何以 xamarin 形式更新可观察集合

c++ - 带有 Xaml 应用程序的 Directx 工具包

c# - 控制 MVVM 中的 View

c# - 调试资源字符串不可用(Silverlight + MonoMac)

c# - 如何拦截导航栏后退按钮单击 Prism Xamarin Forms?

c# - 输入显示和隐藏密码