Hugo
Hugo

Reputation: 134

How can I add string to binding value of image source?

Hi everyone I'm developing a xamarin app and I have a problem. I have the next code in xaml:

<ListView x:Name="listName">
  <ListView.ItemTemplate>
    <DataTemplate>
      <ViewCell>
        <StackLayout Orientation="Vertical">
          <Image Source="{Binding imageName}"></Image>
          <Label Text="{Binding name}" TextColor="Black"></Label>
        </StackLayout>
      </ViewCell>
    </DataTemplate>
  </ListView.ItemTemplate>
</ListView>

I need to change the image source property adding a string. For example:

<Image Source="{Binding imageName} + mystring.png"></Image>
<Image Source="{Binding imageName + mystring.png}"></Image>

Can I do this in xaml? any idea? is possible?

Upvotes: 1

Views: 897

Answers (2)

Jone Schotten
Jone Schotten

Reputation: 1

You could do this in a much simpler way:

<Image Source="{Binding imageName, StringFormat='{0}mystring.png'}"></Image>

Upvotes: 0

Cheesebaron
Cheesebaron

Reputation: 24460

You could use a converter to do this.

public class ImagePostfixValueConverter 
    : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var path = value as string;
        var postfix = parameter as string;

        if (string.IsNullOrEmpty(postfix) || string.IsNullOrEmpty(path))
            return value;

        return path + postfix;
    }

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

Then on your page add:

<ContentPage.Resources>
    <ResourceDictionary>
        <local:ImagePostfixValueConverter x:Key="PostfixConverter"/>
    </ResourceDictionary>
</ContentPage.Resources>

And then in your binding:

<Image Source="{Binding imageName, Converter={StaticResouce PostfixConverter}, ConverterParameter=mystring.png}"></Image>

Upvotes: 2

Related Questions