Xamarin.Forms XAML 图像作为根元素

Xamarin.Forms XAML Image as root element

我是 XAML 的新手,无论我读到什么,人们通常都会使用某种容器作为根视图(StackLayout、ContentPage、ContentView、RelativeLayout 等)。

但是,我 运行 进入这个使用图像作为其根的 XAML。我们为什么要这样做?

<?xml version="1.0" encoding="utf-8" ?>
<Image
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:r="clr-namespace:My.Resources;assembly=My.Resources"
    x:Class="My.Views.Buttons.MyView"
        Source="MyImage.png"/>

我想用 FFImageLoading.CachedImage 替换此图像,但为此我需要添加 FFImageLoading xmlns 命名空间,但我不能,因为命名空间在图像标记内部,而不是外部。

您可以在根标签中指定命名空间,并在 XAML 的根标签中使用它。

例如:

<ffimageloading:CachedImage xmlns="http://xamarin.com/schemas/2014/forms" 
             xmlns:ffimageloading="clr-namespace:FFImageLoading.Forms;assembly=FFImageLoading.Forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="SomeAppNameSpace.CustomCachedImage" 
             Source="http://loremflickr.com/600/600/nature?filename=simple.jpg">
</ffimageloading:CachedImage>

只需确保您在后面的代码中从正确的 class 派生:

namespace SomeAppNameSpace
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class CustomCachedImage : CachedImage
    {
        public CustomCachedImage()
        {
            InitializeComponent();
        }
    }
}