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
  • 1
    Possible duplicate: stackoverflow.com/questions/350027/… Commented Jun 28, 2011 at 8:07
  • 3
    While Silverlight and WPF are similar in many ways, I wouldn't say this is a duplicate. Especially when it comes to resource location. Commented Jun 28, 2011 at 8:33

6 Answers 6

87

Try this:

BitmapImage image = new BitmapImage(new Uri("/MyProject;component/Images/down.png", UriKind.Relative));
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, so basically, it is the Uri class that does the conversion, depending on what is specified in a string. Didn't know that.
Then: myImg.Source = image; If you specify an absolute path, remember to set it to UriKind.Absolute.
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".

Comments

7

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

Comments

3
{yourImageName.Source = new BitmapImage(new Uri("ms-appx:///Assets/LOGO.png"));}

LOGO refers to your image

Hoping to help anyone. :)

Comments

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);

Comments

-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 Comment

Note that the tag for the question says Silverlight. I am not doing anything in ASP. But thanks for the reply, anyway.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.