我正在尝试在我的解决方案中的共享项目中上传图像,以便 Android 和 iOS 项目可以通过 Xaml 正常使用它。不工作,我不知道为什么。谁能解释为什么它不起作用?
扩展名:
[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;
}
}
Xaml:
<Image Source="{extensions:ImageResource MyProject.Assets.fechar.png}" HorizontalOptions="Start" HeightRequest="16" Focused="Image_Focused" BackgroundColor="Red" WidthRequest="15" />
在扩展中放置一个断点,它通常会为我列表中的每个项目设置一次断点。
我还尝试通过代码隐藏插入硬编码绑定(bind),仅用于测试,但它也无法使用 ImageSource.FromResource。
图像文件与文档中指示的一样是 EmbedResource。
请您参考如下方法:
不要使用扩展名。有更简单的方法。
根据 Xamarin “目前没有资源标识符的隐式转换,必须使用 ImageSource.FromResource” 和 “因为没有从字符串到 ResourceImageSource 的内置类型转换器,这些类型的图像无法通过 Xaml 原生加载”。所以你不能在 xaml 中指定你的图像是共享的,但你可以使用代码隐藏来绑定(bind)共享图像。
在 xaml 中:
<Image Source="{Binding Image}" HorizontalOptions="Start" WidthRequest="80"/>
然后在代码后面
public ImageSource Image
{
get
{
return ImageSource.FromResource("ButtonRendererDemo.Resources.icon1.png"); //from PCL
}
}
下面是项目结构
///////////////////////////////////////////////////////////////
使用共享项目进行测试。下面是结构
关键是将共享项目的引用添加到调用 FromResource 的 PCL。共享项目被注入(inject) PCL 然后在我的项目结构中是
public ImageSource Image
{
get
{
//return ImageSource.FromResource("ButtonRendererDemo.Resources.icon1.png"); //from PCL
return ImageSource.FromResource("ButtonRendererDemo.Pictures.icon1.png"); //from Shared
}
}
///////////////////////////////////////////////////////////
如果没有任何效果,请使用以下代码查找您的资源。在调用 FromResource 的文件中使用 System.Reflection 添加;然后添加以下代码
var assembly = typeof(App).GetTypeInfo().Assembly;
foreach (var res in assembly.GetManifestResourceNames())
{
System.Diagnostics.Debug.WriteLine("found resource: " + res);
}
你应该在输出窗口中看到类似的东西
找到的资源:someNamespace.Pictures.icon1.png - 这是您需要使用的资源。
你没有回答我关于你的项目结构的问题。那我可以给你一个准确的答案。我怀疑你的图像路径是“MyProject.Droid.Assets.fechar.png”
