使用Xamarin Forms在XAML中将嵌入式资源图像作为ContentPage的背景

3

我第一次尝试使用Xamarin Forms,所以这可能是一个写得不好的问题,请原谅。

我有一张图片作为嵌入式资源: screenshot 我能在XAML中将该图片用作ContentPage的BackgroundImage吗?如何实现?

提前感谢大家。

更新,如此处所建议: https://developer.xamarin.com/guides/xamarin-forms/working-with/images/#Embedded_Images

  1. 我在主页面cs中添加了自定义的xaml标记扩展:
[Xamarin.Forms.ContentProperty("Source")]
public class ImageResourceExtension : Xamarin.Forms.Xaml.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 = Xamarin.Forms.ImageSource.FromResource(Source);

        return imageSource;
    }
}
我现在可以像这样使用图片:
  <StackLayout VerticalOptions="Center" HorizontalOptions="Center">
    <!-- use a custom Markup Extension -->
    <Image Source="{local:ImageResource App2.images.back_01.png}" />
  </StackLayout>
仍然无法回答原始问题,如何将其设置为后台。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App2;assembly=App2"
             x:Class="App2.MainPage"
             BackgroundImage="">

我认为在XAML代码中,你需要使用local:ImageResourceExtension而不是local:ImageResource - Fabrice T
据我观察,BackgroundImage 仅适用于 iOS。 - Fabrice T
2个回答

0

看起来将图像设置为“仅嵌入式资源”在可移植环境中,对于除了BackgroundImage之外的所有图像使用都有效。
如果要用作BackgroundImage,则该图像还必须嵌入到每个平台的资源中(必须选择正确的每个平台Build Action)。
然后,对于BackgroundImage,可以这样引用它:“folder_name/file_name.png”,因此,与其他图像用法相反,这必须做几次而不是一次。

以上解决方案对我有效。如果有人知道如何避免多余操作,请告诉我。


-2

将图片放入文件夹:

对于 Android,放入 Resources/drawable

对于 iOS,放入 Resources

然后尝试

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:App2;assembly=App2"
             x:Class="App2.MainPage"
             BackgroundImage="back01.png">

谢谢回复,但这几乎与下面的解决方案相同。整个重点是仅将图像作为可移植部分中的嵌入式资源使用,而不是每个平台,但对于背景图像似乎不可能。 - Nikola.N

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接