swift droid
swift droid

Reputation: 107

How to set a background image to a Grid in xamarin.forms?

I want to set a background image to my Grid in code behind. I found in internet that we can do using XAML like this.

<?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 >

But how can I set this in code behind. I cannot see anyImage or BackgroundImage property for Grid. Please help me. Thanks

Upvotes: 0

Views: 1366

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39102

You can just create an empty Image element in the Grid and set it.

<Grid>
    <Image x:Name="BackgroundImage" Aspect="AspectFit" />
    <!-- Place here the rest of the layout for the page. -->
</Grid>

And now set it in code:

backgroundImage.Source = ...;

If you are building the whole UI in code, you can do this as well:

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

If your Grid has multiple rows and columns, you will want to set the Grid.ColumnSpan and Grid.RowSpan properties on the image to make it span the whole grid.

Upvotes: 1

Related Questions