【问题标题】:How can I add string to binding value of image source?如何将字符串添加到图像源的绑定值?
【发布时间】:2017-01-05 23:12:50
【问题描述】:

大家好,我正在开发一个 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 中执行此操作吗? 任何想法?有可能吗?

【问题讨论】:

    标签: image xaml xamarin binding imagesource


    【解决方案1】:

    您可以使用转换器来执行此操作。

    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>
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 2019-09-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多