How to change the background of a grid to an image

2019-05-23 22:17发布

问题:

I'm trying to set a background for a grid control in WP7 silverlight, I need to do that programatically, not in the desighn.

I tried something like:

ContentPanel.Background = new BitmapImage(new Uri("Images\Backgrounds\with box\13.jpg", UriKind.Relative));

But of course, I got an error, because on the right hand we should have the type SolidColorBrush.

is there a way to do that?

Thanks..

回答1:

I would firstly recommend that you use a Canvas instead of a Grid. You can do this by deleting the Grid and inserting a Canvas through the Toolbox -> Drag and Drop.

Then, you can use the code as simple as:

ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = new BitmapImage(new Uri("url", UriKind.Relative));
CanvasName.Background = imageBrush;

That will change the background to whatever you want.

Hope that helps.