简体   繁体   中英

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> */
}

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM