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"; 
2

6 Answers 6

85

Try this:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
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. Jun 28, 2011 at 8:38
  • 5
    Then: myImg.Source = image; If you specify an absolute path, remember to set it to UriKind.Absolute. Jun 25, 2015 at 17:21
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".

0
7

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));
3
{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

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);
0
-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"; 
1
  • 1
    Note that the tag for the question says Silverlight. I am not doing anything in ASP. But thanks for the reply, anyway. Jun 28, 2011 at 8:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.