Reputation: 6337
I have a problem: I want to set the image of my grid through code behind.
Can anybody tell me how to do this?
Upvotes: 56
Views: 168623
Reputation: 961
In order to avoid path problem, you can simply try this, just keep background image in images folder and add this code
<Grid>
<Grid.Background>
<ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
AlignmentY="Top" AlignmentX="Center"/>
</Grid.Background>
</Grid>
Upvotes: 3
Reputation: 12934
Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
</Grid.Background>
<...>
</Grid>
Upvotes: 73
Reputation: 1779
All of this can easily be acheived in the xaml by adding the following code in the grid
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>
</Grid.Background>
</Grid>
Left for you to do, is adding a folder to the solution called 'Images' and adding an existing file to your new 'Images' folder, in this case called 'bg.png'
Upvotes: 81
Reputation: 3091
I have my images in a separate class library ("MyClassLibrary") and they are placed in the folder "Images". In the example I used "myImage.jpg" as the background image.
ImageBrush myBrush = new ImageBrush();
Image image = new Image();
image.Source = new BitmapImage(
new Uri(
"pack://application:,,,/MyClassLibrary;component/Images/myImage.jpg"));
myBrush.ImageSource = image.Source;
Grid grid = new Grid();
grid.Background = myBrush;
Upvotes: 34