xamarin - 有什么方法可以在 UWP 中设置来自 .standard 类库的图像源
问题描述
我创建了 Xamarin Native App,仅使用 .net 标准类库创建 UI 部分平台特定和共享代码(模型、视图模型)。在 UWP 项目中,我像这样设置源路径
Source="pack://application:,,,/MyClassLibraryName;Component/Assets/AppLogo.png"
它对我不起作用!
解决方案
我已经创建 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" />
推荐阅读
- javascript - 来自 WEB API 的 Javascript 类
- javascript - 如何检查当前纬度/经度是否在给定纬度/经度的 20 公里范围内
- angularjs - AngularJS HTTP Post 仍然显示错误 - 工作示例需要
- c++ - 类中的c ++函数在主函数中不起作用
- java - Micronaut Consul 客户端和重试支持
- java - 如何解决此错误: Object 类型中的 toString() 方法不适用于参数?
- c# - Linq 语法:SubmitChanges() 方法不影响数据库,而只影响 DataContext
- node.js - 如何在nodejs的代码中对计算进行单元测试?
- javascript - 如何在 React 应用程序中隐藏 reCaptcha-v2 SITE_KEY
- java - 将字节数组从csv文件的列转换为java中的字节[]