首页 > 解决方案 > 有什么方法可以在 UWP 中设置来自 .standard 类库的图像源

问题描述

我创建了 Xamarin Native App,仅使用 .net 标准类库创建 UI 部分平台特定和共享代码(模型、视图模型)。在 UWP 项目中,我像这样设置源路径

Source="pack://application:,,,/MyClassLibraryName;Component/Assets/AppLogo.png" 

它对我不起作用!

标签: xamarinuwp

解决方案


我已经创建 Xamarin Native App 仅使用 .net 标准类库创建 UI 部分平台特定和共享代码(模型、视图模型)

对于这种情况,您可以参考此文档以从 .net 标准类库ImageResourceExtension中加载 图像。Embedded

我们需要将以下代码添加到.net 标准类库中。

[Preserve(AllMembers = true)]
[ContentProperty(nameof(Source))]
public class ImageExtension : 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(ImageExtension).GetTypeInfo().Assembly);

        return imageSource;
    }
}

然后将图像文件添加到 .net 标准类库并将 Build Action 编辑为Embedded

用法

ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
            xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
            xmlns:mySource="clr-namespace:ImageLib;assembly=ImageLib"
            x:Class="WorkingWithImages.EmbeddedImagesXaml">
   <StackLayout Margin="20,35,20,20">
       <Image Source="{mySource:Image ImageLib.logo.jpg}" />
   </StackLayout>
/ContentPage>

请注意:图片路径为classlibname.imagename.jpg

更新

例如,您可以使用 uwp uri 方案将图像路径添加到图像控件

<ImageBrush ImageSource="ms-appx:///Image/AppLogoicon.png" Stretch="UniformToFill" x:Name="Image" />

推荐阅读