views:

232

answers:

1

I have images scattered throughout my silverlight app, and because of the structure we decided on, all images are brought in from an HTTP URL.

Currently, in XAML an image would be declared as follows:

<Image Source="http://www.example.com/directory/example.png" />

I would like the base URL for all images referenced stored in a global string constant, accessable from all XAML files and code behind files.

i.e. const string BASE_URI = "http://www.example.com/directory";

How can I do this and reference it in XAML, while appending the string to the actual image name? I thought of using a converter, but that requires data binding - and here I am just using the string directly.

A: 

There isn't a way to acheive what you want without some significant code. The simplest solution, as you have already thought of, is to use a converter. It is true that this requires data binding so it isn't as clean a static value on the source property. However since a static value on the source property just is already an issue its hardly a reason to avoid the approach. Here is my prefered solution:-

Converter:-

public class BaseUriConverter : IValueConverter
{
 private Uri myBaseUri;

 public BaseUriConverter()
 {
  myBaseUri = new Uri(Application.Current.Host.Source.AbsoluteUri); 
 }
 public string AdjustPath { get; set; }

 public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
  Uri uri = new Uri(myBaseUri, AdjustPath);
  Uri result = new Uri(uri, (string)parameter);
  return result.ToString();
 }

 public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
 {
  throw new NotImplementedException("This converter only works for one way binding");
 }
}

In the resource in App.Xaml:-

<local:BaseUriConverter x:Key="BaseUri" AdjustPath=".." />

Note that the use of ".." allows for the typical usage. Where the Xap is in a Clientbin folder of the application folder. Hence images can be stored in a common folder relative to the application folder and this works whether the site is run in Visual Studio or installed as a root site in IIS.

Then an image in a page somewhere can look like this:-

<Image DataContext="0" Source="{Binding Converter={StaticResource BaseUri}, ConverterParameter='images/Test.jpg' }"  />

Note the DataContext prorperty is set hence binding happens, the converter isn't bother what the value is. Also the path is relative in this case.

In your specific example you could assign in code your fixed baseURL to the AdjustPath property of the converter however I suspect that as it stands this will suit your needs.

AnthonyWJones