Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I format a URI when binding an Image in Silverlight?

I haven't been able to find an answer to this.

I have a database that has image paths in it ("images/myimage.jpg"). These images exist on my asp.net site which is also where I host the SL. I want to bind these images to my ListBox control so that the image displays.

I have read that since I have a string value, "images/myimage.jpg", that I need to convert it to a BitMap image. I have done this:

The xaml:

 <Image Source="{Binding ImageFile, Converter={StaticResource ImageConverter}}"/>

The ImageConverter class:

    public object Convert(object value, Type targetType,
                                  object parameter, CultureInfo culture)
            {
                try
                {
                    Uri source= new Uri(value.ToString());
                    return new BitmapImage(source);
                }
                catch(Exception ex)
                {
                    return new BitmapImage();
                }
            }

I get an error when creating the URI, "The Format of the URI could not be determined". What am I doing wrong? If I create a Uri that looks like this: http://localhost:49723/images/myimage.jpg, it works just fine.

Why doesn't just "images/myimage.jpg" work?

like image 455
ScottG Avatar asked Dec 28 '25 22:12

ScottG


1 Answers

A simple, dynamic approach that will work regardless of where your XAP file is located is similar to the following.

//Get the root path for the XAP
string src = Application.Current.Host.Source.ToString();

//Get the application root, where 'ClientBin' is the known dir where the XAP is
string appRoot = src.Substring(0,src.IndexOf("ClientBin")); 

//Create the image / uri
BitmapImage img = new BitmapImage();
img.UriSource = new Uri(appRoot + "/Images/myImage.png", UriKind.Relative);

Does this help?

like image 111
PortageMonkey Avatar answered Dec 31 '25 14:12

PortageMonkey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!