【问题标题】:is there any way to set Source for Image From .standard Class Library in UWP有什么方法可以在 UWP 中设置来自 .standard 类库的图像源
【发布时间】:2020-11-27 11:43:55
【问题描述】:

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

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

它不适合我!

【问题讨论】:

  • 在 UWP 项目中,我设置了这样的源路径

标签: xamarin uwp


【解决方案1】:

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

对于这种情况,您可以参考这个document 使ImageResourceExtension 从.net 标准类库中加载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 scheme 来添加图片路径到图片控件,例如

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

【讨论】:

  • 如您提供的代码,如果我们在 UWP 平台中使用 ContentPage,则支持,如果我们 UserControl,则不支持。
  • 用户控制?你写的代码、表单或者uwp客户端在哪里?
  • 嗨,我正在尝试使用本机 UI 创建 xamarin 演示项目,为此我最初创建了 .net 标准类库并添加了新的 UWP 项目,我试图从类库文件夹中提供图像源路径在 UWP Xmal 中
  • 这是我的 UWP Xmal schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UwpNativeUi" xmlns :d="schemas.microsoft.com/expression/blend/2008">
  • 感谢 Nico Zhu 这对我有用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
相关资源
最近更新 更多