Visual C#:Metro应用程序更改背景(以编程方式)

时间:2014-02-25 20:19:04

标签: c# xaml windows-8 windows-store-apps

C#中是否有改变当前页面(或网格)背景的功能?

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

2 个答案:

答案 0 :(得分:1)

试试这段代码:

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

grd是您的网格名称。

答案 1 :(得分:1)

LayoutRoot是您的网格名称,您可以设置这样的背景:

    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;