I have a problem: I want to set the image of my grid through code behind.
Can anybody tell me how to do this?
Just put the grid panel inside a canvas rather than directly into the window - this will then give it X/Y co-ordinates.
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'
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>
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;
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With