Silverlight ImageSourceConverter

by Rob 19. November 2008 13:54

The Silverlight 2 converter below will convert from a string to a absolute uri in order to stream the images from the website instead of retrieving them from the XAP file.

One of the reasons to do this was a side-effect in Silverlight. For example, when you have a folder within your silverlight project named 'Controls', and you bind an image path to 'Images/Test.png', the resulting image will be loaded from 'Controls/Images/Test'. To overcome this behaviour, I trim the folder name from the request path and transform the relative images to an absolute url.

 

Here's the code:

[code]

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;
using System.Windows.Interop;

namespace Silverlight.Controls.Converters
{
    /// <summary>  
    /// A type converter for changing any image url to the root of the web application
    /// </summary>  
    public class ImageSourceConverter : IValueConverter
    {
        public object Convert(
            object value,
            Type targetType,
            object parameter,
            CultureInfo culture)
        {
            Uri hostUri = Application.Current.Host.Source;

            //first, get the host,
            string host = hostUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);

            string path = hostUri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped);

            //remove /clientbin/...
            path = path.Substring(0, path.IndexOf("/ClientBin"));
            path = System.IO.Path.Combine(path, (string)value);

            //now combine host and path.
            Uri newUri = new Uri(new Uri(host), path);

            return new BitmapImage(newUri);
        }

        public object ConvertBack(
            object value,
            Type targetType,
            object parameter,
            CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
}

[/code]

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

C# | Silverlight

Powered by BlogEngine.NET 1.4.0.0
Theme by Mads Kristensen

About the author

Some text that describes me

Recent comments

Comment RSS

Page List

    Disclaimer

    The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

    © Copyright 2008