Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background image on grid in WPF using C#

Tags:

c#

wpf

I have a problem: I want to set the image of my grid through code behind.

Can anybody tell me how to do this?

like image 980
Shashank Avatar asked Jun 23 '10 10:06

Shashank


People also ask

How do I move the grid in WPF?

Just put the grid panel inside a canvas rather than directly into the window - this will then give it X/Y co-ordinates.


4 Answers

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'

like image 91
Jan Avatar answered Sep 30 '22 03:09

Jan


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>
like image 23
Amsakanna Avatar answered Oct 02 '22 03:10

Amsakanna


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;          
like image 23
AH. Avatar answered Sep 28 '22 03:09

AH.


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>
like image 40
Tazwar Utshas Avatar answered Sep 28 '22 03:09

Tazwar Utshas