30

I am dynamically generating an image through code-behind in Silverlight and apparently the image source doesn't accept a string or Uri as a path.

How can I set the source?

2
  • This took me a little while to figure out too. Guantam's answer looks like what I used. Commented Feb 23, 2009 at 17:56
  • I had to change it a bit though, it worked without including the namespace in the path Commented Feb 23, 2009 at 18:41

3 Answers 3

54

How do you mean it won't accept a string as source?

Are you not able to do this?

Or are you saying your image is in memory and you don't know how to reference it?

this.MyImage.Source = new BitmapImage(new Uri("/MyNameSpace;images/someimage.png", UriKind.Relative));
Sign up to request clarification or add additional context in comments.

2 Comments

Doesnt accept string i meant for example: MyImage.Source = "/MyNameSpace;images/someimage.png" like in asp.net
my project needs to append "components": this.MyImage.Source = new BitmapImage(new Uri("/MyNameSpace;components/images/someimage.png", UriKind.Relative));
6
// create a new image
Image image = new Image();

// better to keep this in a global config singleton
string hostName = Application.Current.Host.Source.Host;                   
if (Application.Current.Host.Source.Port != 80)
    hostName += ":" + Application.Current.Host.Source.Port;

// set the image source
image.Source = new BitmapImage(new Uri("http://" + hostName + "/image111.jpg", UriKind.Absolute));  

1 Comment

no need to go for HTTP protocol. just use local resource is fine.
1

I needed to replace the following to get the solution work:

this.MyImage.Source = new BitmapImage(new Uri("/MyNameSpace;components/images/someimage.png", UriKind.Relative));

MyNameSpace did not work for me, but the ExecutingAssemblyName did, so:

Dim tmp As String() = Assembly.GetExecutingAssembly.FullName.Split(","c)
Dim path As String = "/" & tmp(0) & ";component/images/"
MyImage.Source = new BitmapImage(new Uri(path & "someImage.png"))

Comments

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.