How do I reference the base URLs for images in XAML in Silverlight?

I have images scattered throughout my silverlight application, and due to the structure we decided, all images are imported from the HTTP URL.

Currently, in XAML, the image will be declared as follows:

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

I would like the base URL for all image links stored in the global string constant to be accessible from all XAML files and code behind the files.

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

How can I do this and reference it in XAML by adding a string to the name of the actual image? I was thinking about using a converter, but that requires data binding, and here I just use the string directly.

+3
source share
1 answer

There is no way to achieve what you want without any meaningful code. The easiest solution, as you already thought, is to use a converter. It is true that this requires data binding, so this is not a pure static value for the source property. However, since the static value of the source property is simply already a problem, this is hardly the reason to avoid the approach. Here is my preferred 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 a resource in App.Xaml: -

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

, ".." . Xap Clientbin . , , , Visual Studio IIS.

- : -

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

, DataContext , , , , . .

baseURL AdjustPath , , , , .

+2
source

Source: https://habr.com/ru/post/1722559/


All Articles