0

I have an image ("test1.png") in the Resources folder... in XAML, I can set an image by using:

<Image Name="myImage" Source="Resources/test1.png" />

Now I have another image ("test2.png") in the Resources folder, how do I set myImage to "test2.png" in the code behind?

I googled and found solutions that seem pretty complex for such a trival task, by using Reflection during runtime. Is there a simpler solution?

Darren Ng
  • 373
  • 1
  • 5
  • 20
  • http://stackoverflow.com/questions/350027/setting-wpf-image-source-in-code – iceheaven31 Aug 30 '13 at 02:56
  • I cannot use that solution. My project is created as a UserControl, which another main project would use. Therefore, my project does not have an assembly. – Darren Ng Aug 30 '13 at 03:18
  • what do you mean you UserControl does not have an assembly, how are people going to use it, just copy the source code to thier project?, perhaps you need to read up on how Pack-URI's work: http://msdn.microsoft.com/en-us/library/aa970069.aspx – sa_ddam213 Aug 30 '13 at 03:27
  • Have you seen the chosen answer to that question? It gives the way on how to dynamically set an image in code. You can use the same code and just have the url of the image passed through the user control's property. – iceheaven31 Aug 30 '13 at 03:27
  • I think in order to access a XAML object from code-behind you need a `x:Name` attribute. – Mathieu Guindon Aug 30 '13 at 03:35

1 Answers1

0

I use this

BitmapImage test2=
            new BitmapImage(new Uri("pack://application:,,,/Resources/test2.png", UriKind.Absolute));
myImage.Source = test2;

edit: Just saw someone posted a link to basically the same solution already. If you are in a library also use the assembly name in the Uri.

metacircle
  • 2,438
  • 4
  • 25
  • 39