【问题标题】:Xamarin XAML StaticResource inside another one另一个里面的 Xamarin XAML StaticResource
【发布时间】:2017-10-25 15:48:36
【问题描述】:

我在 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;
        }
    }
}

谢谢!

【问题讨论】:

    标签: c# xaml xamarin xamarin.ios staticresource


    【解决方案1】:

    在 App.cs 中

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

    XAML:

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

    图像资源扩展

    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:确保图片的 Build Action 为 Embedded Resource

    【讨论】:

    • 谢谢,但是,您在发布之前尝试过吗?因为不工作..
    • @Jackpot21 我试过了,效果很好。请确保您可以通过字符串访问图像
    • @Jackpot21 我在uwp项目中测试,图片放在根文件夹
    • 谢谢,不过PCL项目里面有图片,单平台项目里面没有。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 2011-06-12
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多