2

I have a BitmapImage, and want to set it as Background of Grid. I have tried this

xaml:

<Grid x:Name="ContentPanel">
    <Grid.Background>
        <ImageBrush x:Name="imgBg" />
    </Grid.Background>
</Grid>

c#:

        BitmapImage bmp = new BitmapImage();
        bmp.DecodePixelWidth =(int) scrnWidth;
        bmp.DecodePixelHeight = (int)scrnHeight;
        bmp.SetSource(e.ChosenPhoto);

        ImageBrush ib = new ImageBrush() { ImageSource = bmp };
        imgBg.ImageSource = ib.ImageSource;

Output: Output is just black.

Question: using above code I am unable to set bitmapimage as background of Grid element, Am I missing something ?

Update I knew, it works fine when we set image as background to grid like:

ImageBrush ib = new ImageBrush() { ImageSource = bmp };
ContentPanel.Background = ib;

But I need to use xaml way, Question is same.

Dev
  • 1,130
  • 10
  • 21
  • 1
    Is there some special reason why you are using a bitmapImage? – Carsten Løvbo Andersen Nov 04 '14 at 10:51
  • just because it takes less memory and allow to scale down the size of image. https://social.msdn.microsoft.com/Forums/windowsapps/en-US/6b8d2d70-b372-486d-92b0-c09556d6a5a4/how-to-clear-memory-used-by-writeablebitmapimage?forum=wpdevelop – Dev Nov 04 '14 at 10:52
  • 1
    I've tested this code and it works as is, properly setting the background of the grid. The problem must be somewhere else - the layout of the grid (its children cover it completely)? – lisp Nov 04 '14 at 13:12
  • @lisp have you tested as contentpanel.background=bmp ?, have a look at updated question – Dev Nov 05 '14 at 06:13
  • 1
    i've tested the first two code fragments. it worked for a picture from PhotoChooserTask. – lisp Nov 05 '14 at 11:36

1 Answers1

1
<Grid x:Name="ContentPanel">
    <Grid.Background>
        <ImageBrush Stretch="None" 
                    ImageSource="Your Path/source" 
                    AlignmentY="Center" 
                    AlignmentX="Center" />
    </Grid.Background>
</Grid>

This might help you, cant promise you it will but try it. was found on this post. Here

Community
  • 1
  • 1
Carsten Løvbo Andersen
  • 26,637
  • 10
  • 47
  • 77