How to programmatically set the Image source
Asked Answered
C

6

44

When the Image's Source property is set the following way, the picture is taken from /Images/down.png.

How would I do the same thing programmatically?

<Image x:Name="myImg" Source="/MyProject;component/Images/down.png" />

The following would not work, since Image.Source property is not of a string type.

myImg.Source = "/MyProject;component/Images/down.png"; 
Cutie answered 28/6, 2011 at 8:5 Comment(2)
Possible duplicate: #350527Foreclose
While Silverlight and WPF are similar in many ways, I wouldn't say this is a duplicate. Especially when it comes to resource location.Cutie
H
86

Try this:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
Harewood answered 28/6, 2011 at 8:7 Comment(2)
Oh, so basically, it is the Uri class that does the conversion, depending on what is specified in a string. Didn't know that.Cutie
Then: myImg.Source = image; If you specify an absolute path, remember to set it to UriKind.Absolute.Gittel
L
17
myImg.Source = new BitmapImage(new Uri(@"component/Images/down.png", UriKind.RelativeOrAbsolute)); 

Don't forget to set Build Action to "Content", and Copy to output directory to "Always".

Lancet answered 13/1, 2015 at 15:35 Comment(0)
D
7

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));
Decor answered 11/12, 2015 at 18:23 Comment(0)
M
3
{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

Mentalist answered 4/10, 2015 at 0:58 Comment(0)
S
0

try this

PictureBox picture = new PictureBox
        {
            Name = "pictureBox",
            Size = new Size(100, 50),
            Location = new Point(14, 17),
            Image = Image.FromFile(@"c:\Images\test.jpg"),
            SizeMode = PictureBoxSizeMode.CenterImage
        };
p.Controls.Add(picture);
Spancake answered 14/8, 2013 at 14:23 Comment(0)
T
-1

Use asp:image

<asp:Image id="Image1" runat="server"
           AlternateText="Image text"
           ImageAlign="left"
           ImageUrl="images/image1.jpg"/>

and codebehind to change image url

Image1.ImageUrl = "/MyProject;component/Images/down.png"; 
Turves answered 28/6, 2011 at 8:8 Comment(1)
Note that the tag for the question says Silverlight. I am not doing anything in ASP. But thanks for the reply, anyway.Cutie

© 2022 - 2024 — McMap. All rights reserved.