另外一个Xamarin XAML StaticResource

时间:2017-10-25 15:48:36

标签: c# xaml xamarin xamarin.ios staticresource

我在App.xaml的ResourceDictionary中有一个字符串。

<x:String x:Key="logoEvo">.Images.logoEvo.png</x:String>

如何在另一个StaticResource中使用它,如下所示:

<Image Source="{sgat:ImageResource SgatMobileOnline{StaticResource logoEvo} }" />

ImageResource的文件是:

using System;
using Xamarin.Forms;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Xaml;

namespace SgatMobileOnline {

    // You exclude the 'Extension' suffix when using in Xaml markup
    [Preserve(AllMembers = true)]
    [ContentProperty("Source")]
    public class ImageResourceExtension : IMarkupExtension {
        public string Source { get; set; }

        public object ProvideValue(IServiceProvider serviceProvider) {
            if (Source == null) {
                return null;
            }
            // Do your translation lookup here, using whatever method you require
            var imageSource = ImageSource.FromResource(Source);

            return imageSource;
        }
    }
}

谢谢!

1 个答案:

答案 0 :(得分:2)

在App.cs中

 <Application.Resources>
    <ResourceDictionary>
        <x:String x:Key="logoEvo">test.png</x:String>
    </ResourceDictionary>
</Application.Resources>

XAML:

<Image Source="{local:ImageResourceExtension logoEvo}" />

ImageResourceExtension

namespace App1
{
[Preserve(AllMembers = true)]
[ContentProperty("Source")]
public class ImageResourceExtension : IMarkupExtension
{
    public string Source { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Source == null)
        {
            return null;
        }

        string s = Application.Current.Resources[Source] as string;
        // Do your translation lookup here, using whatever method you require

        var assembly = typeof(ImageResourceExtension).GetTypeInfo().Assembly;
        var assemblyString = assembly.GetName().Name.ToString();
        var imageSource = ImageSource.FromResource(assemblyString + "." + s);
        return imageSource;
    }
}
}

PS:确保图像的构建操作为嵌入式资源