如何从XAML引用嵌入式资源
本文关键字:嵌入式 资源 引用 XAML | 更新日期: 2023-09-27 18:25:48
我有几个图像要嵌入到exe中。
当我将构建操作设置为嵌入资源时我在代码中找到了一个资源不可用的错误,并要求我将构建操作设置为Resource
我尝试了几种不同的方法:
<ImageSource x:Key="Image_Background">YearBook;component/Resources/Images/darkaurora.png</ImageSource>
<ImageSource x:Key="Image_Background">Images/darkaurora.png</ImageSource>
<ImageSource x:Key="Image_Background">pack://application:,,,/Resources/Images/darkaurora.png</ImageSource>
此代码位于Resource文件中。但没有一个奏效,他们都抛出了这个错误:
Cannot convert the string 'pack://application:,,,/Resources/Images/darkaurora.png' into a 'System.Windows.Media.ImageSource' object. Cannot locate resource 'resources/images/darkaurora.png'. Error at object 'Image_Background' in markup file 'YearBook;component/Resources/ImageResources.xaml' Line 4 Position 6.
在代码的不同位置,我得到:
the file 'YearBook;component/Resources/Images/shadowdrop.png' is not a part of the project or its 'Build Action' property is not set to 'Resource'
那么,我做错了什么?
当您将BuildAction设置为Resource时,它将作为程序集中的嵌入资源。或者,您可以将BuildAction设置为Content,然后它将绑定到生成的.xap文件中。您可以使用这些BuildActions中的任何一个。通过将BuildAction设置为Content,您可以访问以下图像:"/Resources/Images/darkaurora.png"
(必须以斜线开头)。当您使用BuildAction资源时,您可以以"/YearBook;component/Resources/Images/darkaurora.png"
(assemblyname;component/rerelativepath)的形式访问映像。希望这会有所帮助。
对于那些使用xamarin表单并遇到这个问题的人来说,这可以通过创建一个自定义的xaml标记扩展来完成,如下所述:
https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/images?tabs=windows
在"嵌入式图像"->"使用XAML"部分
引用自定义扩展
[ContentProperty (nameof(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, typeof(ImageResourceExtension).GetTypeInfo().Assembly);
return imageSource;
}
}
如何使用的引文
<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:WorkingWithImages;assembly=WorkingWithImages"
x:Class="WorkingWithImages.EmbeddedImagesXaml">
<StackLayout VerticalOptions="Center" HorizontalOptions="Center">
<!-- use a custom Markup Extension -->
<Image Source="{local:ImageResource WorkingWithImages.beach.jpg}" />
</StackLayout>
</ContentPage>
ImageSource无法实例化。
public abstract class ImageSource : Animatable,
IFormattable
里面有一个小小的abstract
,它会把你的一天搞砸的。您的xaml实际上正在尝试实例化ImageSource的一个实例,然后使用可以定位的任何转换器将元素(在本例中为Uri)中的值分配给用ContentPropertyAttribute(??)标记的属性,以将字符串转换为对象(再次,??)。
我想你想要一个BitmapSource。
<BitmapImage
x:Key="Image_Background"
UriSource="/Images/darkaurora.png" />