如何在xamarin.forms中将背景图像设置为网格?

如何在xamarin.forms中将背景图像设置为网格?,xamarin.forms,grid,background-image,Xamarin.forms,Grid,Background Image,我想在代码隐藏中为网格设置背景图像。我在互联网上发现,我们可以像这样使用XAML <?xml version="1.0" encoding="UTF-8"?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Pages.PhotoPage"> <Grid >

我想在代码隐藏中为网格设置背景图像。我在互联网上发现,我们可以像这样使用XAML

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="Pages.PhotoPage">
    <Grid >
        <Image Source="background.png" Aspect="AspectFit" />
        <!-- Place here the rest of the layout for the page. -->
    </Grid >
但是我如何在代码隐藏中设置它呢。我看不到网格的任何图像或背景图像属性。请帮帮我。
谢谢

您只需在网格中创建一个空图像元素并进行设置

<Grid>
    <Image x:Name="BackgroundImage" Aspect="AspectFit" />
    <!-- Place here the rest of the layout for the page. -->
</Grid>
如果要用代码构建整个UI,也可以这样做:

var myGrid = new Grid();
var backgroundImage = new Image();
backgroundImage.Source = ...;
myGrid.Children.Add( backgroundImage );
如果网格有多个行和列,则需要在图像上设置Grid.ColumnSpan和Grid.RowSpan属性,使其跨越整个网格

var myGrid = new Grid();
var backgroundImage = new Image();
backgroundImage.Source = ...;
myGrid.Children.Add( backgroundImage );