如何将字符串添加到图像源的绑定值?

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

大家好,我正在开发 xamarin 应用程序,但遇到了问题。 我在 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>

我需要更改图像源 属性 添加字符串。例如:

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

我可以在 xaml 中执行此操作吗? 任何的想法?可能吗?

您可以使用转换器来完成此操作。

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();
    }
}

然后在您的页面上添加:

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

然后在您的绑定中:

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

你可以用更简单的方法来做到这一点:

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