Anand
Anand

Reputation: 1959

Xamarin forms URL binding on Image

I have a Image in my xaml in which the source is a URL that Iam binding.The URL from json will be like this : "/images/Uploads/e0111.png". I have the URL in my Common values stored class as CommonValues.URL. How can I add this "CommonValues.URL" before the json at the time of binding? So that the source for Image will be http://example.com//images/Uploads/e0111.png.?

Upvotes: 0

Views: 897

Answers (2)

Bruno Caceiro
Bruno Caceiro

Reputation: 7199

You can use a converter, which will allow you to reuse in all your views/application

public class UrlConverter : IValueConverter
{
    #region IValueConverter implementation

    public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        var test = value as string; 
        if (!string.IsNullOrEmpty(test))  
        {
            return CommonValues.URL + test;
        }
        return false;
    }

    public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }

    #endregion
}

Then, in your page:

<ContentPage.Resources>
    <ResourceDictionary>
        <converter:UrlConverter x:Key="UrlConverter" />
    </ResourceDictionary>
</ContentPage.Resources>

<Image Source="{Binding YourProperty, Converter={StaticResource UrlConverter}}"/>

Upvotes: 1

Arvind Chourasiya
Arvind Chourasiya

Reputation: 17452

If you need Uri

var myUrl= new Uri(CommonValues.URL + "images/Uploads/e0111.png");

If string than

var myUrl=CommonValues.URL + "images/Uploads/e0111.png";

Or you can do it like this in your ViewModel or Page

public string Url => string.Format("{0}{1}", CommonValues.URL,"/images/Uploads/e0111.png");

Then in XAML:

<Button Text="{Binding Url}"/>

Upvotes: 1

Related Questions