在 Xamarin.Forms 中使用带有嵌入图像的图标 属性

Use Icon property with embedded images in Xamarin.Forms

我正在研究 shared project and I implemented a Master Detail Page. Now I added an image to the shared project (aka embedded image)。图像的构建操作是 Embedded resource 并且我遵循将命名空间 (HelloForms) 和子文件夹 (Ressources) 考虑在内的建议。结果应如下所示:

如您所见,leftBarButtonItem is set through the Icon property. I tried to set the Icon 属性 如下所示:

Icon = Device.OS == TargetPlatform.iOS ? "HelloForms.Ressources.menu.png" : null;

Icon = new FileImageSource { File = "HelloForms.Ressources.menu.png" };

目前,我显示的是 Master 页面的标题,而不是 Icon。我必须改变什么才能让它工作?我对 嵌入式图像 的解决方案感兴趣,而对 本地图像 的解决方案不感兴趣。

你的代码是错误的,你想使用 ImageSource.FromResource,这是明确为此创建的:

Icon = ImageSource.FromResource("HelloForms.Ressources.menu.png");

编辑:

Icon 是一个 FileStream,因此无法使用 ImageSource。此外,Xamarin 这样做是有充分理由的,该文件将用于在 Android 上代表桌面上的应用程序,因此系统必须可以访问它,并且嵌入式资源不能像在资源文件中那样。

"Embedded resource" 在这里造成混淆,在 iOS 项目上,Xamarin 将默认的 "Content" 操作更改为 "Embedded resource",这导致认为它被嵌入到 .net 中程序集,但没有,它被复制到项目中。

只需将文件作为资源添加到iOS/Android项目中,直接使用文件名即可。

menu.png 被添加到错误的共享项目中。将它添加到 iOS 项目的 Resources 文件夹中(Build Action = BundleResource)似乎可以解决问题。那么你只需要这段代码

Icon = Device.OS == TargetPlatform.iOS ? "menu.png" : null;

让它发挥作用。看来我误解了 Embedded Images