views:

57

answers:

2

I am trying to bind an image source to my XAML through c#

this works

<Image Source="images/man.jpg"></Image>

this does not work

<Image Source="images/{Binding imagesource}"></Image>

where imagesource is a string variable in the c# file of this xaml and is being set equal to "man.jpg"

A: 

imagesource needs to be an actual Image object, not a string.

Here is a method that will create a new Image object given a path:

public BitmapImage Load(string path)
{
    var uri = new Uri(path);
    return new BitmapImage(uri);
}
DanM
this does not work for some reason. My app refuses to load it just gets stuck at 100%
nooob
Did you try the full path or the relative path? Should be full path. Also, I know my method works in WPF...perhaps it doesn't work in Silverlight for some reason.
DanM
+1  A: 

You can't stick a binding mid-way through the value like that. It's either a binding, or it's not. Assuming imagesource is publicly accessible via your DataContext, you could do this:

<Image Source="{Binding imagesource}"/>

However, if it's been set to "man.jpg" then it won't find the image. Either set imagesource to the full path ("images/man.jpg") or use a converter:

<Image Source="{Binding imagesource, Converter={StaticResource RelativePathConverter}}"/>

The converter would prepend "images/" onto its value. However, it may be necessary for the converter to return an ImageSource rather than a string.

HTH,
Kent

Kent Boogaart
I changed imagesource to the full path "images/man.jpg" it is still not working. What do you mean it should be publicly accessible in the DataContext? I changed its access modifier to public and made get function for it as well, still doesnt work.
nooob
What is your DataContext? Have you set it? Look for binding errors in Visual Studio's output window.
Kent Boogaart