KeksArmee
KeksArmee

Reputation: 1429

Visual C#: Metro app change background (Programmatically)

Is there a function in C# that changes the background of the current page (or grid)?

C#:

int hourOfDay = DateTime.Now.Hour;
if(hourOfDay <= 12 && hourOfDay >= 18) {
    /* Set background to afternoon_bg.jpg
     * 
     * In XAML:
     * <Grid.Background>
     *     <ImageBrush ImageSource="/Assets/afternoon_bg.jpg" Stretch="UniformToFill" />
     * </Grid.Background> */
}
if(hourOfDay <= 6 && hourOfDay >= 12) {
    /* Set background to morning_bg.jpg
     * 
     * In XAML:
     * <Grid.Background>
     *     <ImageBrush ImageSource="/Assets/morning_bg.jpg" Stretch="UniformToFill" />
     * </Grid.Background> */
}

Upvotes: 1

Views: 594

Answers (2)

Chris Shao
Chris Shao

Reputation: 8231

LayoutRoot is your grid name, you can set background like this:

    int hourOfDay = DateTime.Now.Hour;
    ImageBrush ib = new ImageBrush();
    if(hourOfDay >= 12 && hourOfDay < 18) {
        ib.ImageSource = new BitmapImage( new Uri("ms-appx:///Assets/afternoon_bg.jpg", UriKind.Relative));
    }
    else if (hourOfDay >= 6 && hourOfDay < 12)
    {
        ib.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/morning_bg.jpg", UriKind.Relative));
    }
    else
    {
        // do something
    }
    LayoutRoot.Background = ib;

Upvotes: 1

crea7or
crea7or

Reputation: 4490

Try this code:

ImageBrush ib = new ImageBrush();
ib.ImageSource = new BitmapImage( new Uri(@"\Pictures\profile.jpg", UriKind.Relative));
grd.Background = ib;

grd is your grid name.

Upvotes: 1

Related Questions